blob: 7c7541665bb8af356aa5e284b423a3b415b6e765 [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
TheCodedProf80ad8542023-03-10 12:52:33 -050026
Skyler Grey7a966df2023-03-09 12:53:57 +000027const nsfw_model = await nsfwjs.load("file://dist/reflex/nsfwjs/example/nsfw_demo/public/model/", { size: 299 });
Skyler Greyd1157312023-03-08 10:07:38 +000028const clamscanner = await new ClamScan().init({
29 clamdscan: {
TheCodedProf80ad8542023-03-10 12:52:33 -050030 socket: "socket" in config.clamav ? config.clamav.socket as string : false,
31 host: "host" in config.clamav ? config.clamav.host as string : false,
32 port: "port" in config.clamav ? config.clamav.port as number : false,
Skyler Greyd1157312023-03-08 10:07:38 +000033 }
34});
TheCodedProfd8ef1f32023-03-06 19:15:18 -050035
Skyler Grey74169642023-03-09 11:59:09 +000036export async function testNSFW(url: string): Promise<NSFWSchema> {
37 const [fileStream, hash] = await streamAttachment(url);
Skyler Greyda16adf2023-03-05 10:22:12 +000038 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Greyea0937b2023-03-09 00:36:38 +000039 if (alreadyHaveCheck && "nsfw" in alreadyHaveCheck!) {
40 return { nsfw: alreadyHaveCheck.nsfw };
41 }
TheCodedProfd8ef1f32023-03-06 19:15:18 -050042
Skyler Greyea0937b2023-03-09 00:36:38 +000043 const converted = (await new Promise((resolve, reject) =>
44 gm(fileStream)
45 .command("convert")
46 .toBuffer("PNG", (err, buf) => {
47 if (err) return reject(err);
48 resolve(buf);
49 })
50 )) as Buffer;
TheCodedProfd8ef1f32023-03-06 19:15:18 -050051
Skyler Grey74169642023-03-09 11:59:09 +000052 const img = tf.node.decodeImage(converted, 3, undefined, false) as tf.Tensor3D;
Skyler Grey0d885222023-03-08 21:46:37 +000053
54 const predictions = (await nsfw_model.classify(img, 1))[0]!;
Skyler Grey74169642023-03-09 11:59:09 +000055 img.dispose();
Skyler Grey0d885222023-03-08 21:46:37 +000056 console.log(2, predictions);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050057
Skyler Greyd1157312023-03-08 10:07:38 +000058 const nsfw = predictions.className === "Hentai" || predictions.className === "Porn";
59 await client.database.scanCache.write(hash, "nsfw", nsfw);
60
61 return { nsfw };
pineafan813bdf42022-07-24 10:39:10 +010062}
63
pineafan02ba0232022-07-24 22:16:15 +010064export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey0a4846c2023-03-08 00:32:01 +000065 const [fileName, hash] = await saveAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000066 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey0d885222023-03-08 21:46:37 +000067 if (alreadyHaveCheck?.malware !== undefined) return { malware: alreadyHaveCheck.malware };
Skyler Greyd1157312023-03-08 10:07:38 +000068 let malware;
Skyler Grey0a4846c2023-03-08 00:32:01 +000069 try {
Skyler Greyd1157312023-03-08 10:07:38 +000070 malware = (await clamscanner.scanFile(fileName)).isInfected;
Skyler Grey0a4846c2023-03-08 00:32:01 +000071 } catch (e) {
Skyler Grey0d885222023-03-08 21:46:37 +000072 return { malware: true };
Skyler Grey0a4846c2023-03-08 00:32:01 +000073 }
Skyler Greyf4f21c42023-03-08 14:36:29 +000074 await client.database.scanCache.write(hash, "malware", malware);
Skyler Grey0d885222023-03-08 21:46:37 +000075 return { malware };
pineafan3a02ea32022-08-11 21:35:04 +010076}
77
78export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000079 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey0d885222023-03-08 21:46:37 +000080 if (alreadyHaveCheck?.bad_link !== undefined)
81 return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags ?? [] };
82 return { safe: true, tags: [] };
83 // const scanned: { safe?: boolean; tags?: string[] } = {}
84 // await client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
85 // return {
86 // safe: scanned.safe ?? true,
87 // tags: scanned.tags ?? []
88 // };
pineafan813bdf42022-07-24 10:39:10 +010089}
90
Skyler Grey0d885222023-03-08 21:46:37 +000091export async function streamAttachment(link: string): Promise<[Buffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000092 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey32179982023-03-07 23:59:06 +000093 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +000094 const buf = Buffer.from(image);
95 return [buf, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
Skyler Grey32179982023-03-07 23:59:06 +000096}
97
98export async function saveAttachment(link: string): Promise<[string, string]> {
99 const image = await (await fetch(link)).arrayBuffer();
Skyler Greyf4f21c42023-03-08 14:36:29 +0000100 const fileName = await generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -0500101 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +0000102 writeFileSync(fileName, new DataView(image));
Skyler Grey32179982023-03-07 23:59:06 +0000103 return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +0100104}
105
pineafan813bdf42022-07-24 10:39:10 +0100106const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +0100107 PHISHING: "Links designed to trick users into clicking on them.",
108 DATING: "Dating sites.",
109 TRACKERS: "Websites that store or track personal information.",
110 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100111 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +0100112 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 +0100113 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100114 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100115 PORN: "Websites that include pornography.",
116 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100117 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100118 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100119 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 +0100120 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
121 SCAMS: "Sites which are designed to trick you into doing something.",
122 TORRENT: "Websites that download torrent files.",
123 HATE: "Websites that spread hate towards groups or individuals.",
124 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100125};
pineafan813bdf42022-07-24 10:39:10 +0100126export { linkTypes };
127
pineafan63fc5e22022-08-04 22:04:10 +0100128export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100129 const links =
130 message.content.match(
131 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
132 ) ?? [];
133 const detections: { tags: string[]; safe: boolean }[] = [];
134 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100135 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100136 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100137 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 +0100138 returned = await testLink(element);
139 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100140 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100141 return;
142 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100143 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100144 });
145 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100146 const detectionsTypes = detections
147 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100148 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100149 if (type) return type;
150 // if (!element.safe) return "UNSAFE"
151 return undefined;
152 })
153 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100154 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100155}
156
Skyler Grey74169642023-03-09 11:59:09 +0000157export async function NSFWCheck(url: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100158 try {
Skyler Grey74169642023-03-09 11:59:09 +0000159 return (await testNSFW(url)).nsfw;
Skyler Grey0d885222023-03-08 21:46:37 +0000160 } catch (e) {
Skyler Greyea0937b2023-03-09 00:36:38 +0000161 console.log(e);
pineafan63fc5e22022-08-04 22:04:10 +0100162 return false;
pineafan813bdf42022-07-24 10:39:10 +0100163 }
164}
165
Skyler Grey11236ba2022-08-08 21:13:33 +0100166export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100167 if (element.height === null || element.width === null) return true;
168 if (element.height < 20 || element.width < 20) return false;
169 return true;
pineafan813bdf42022-07-24 10:39:10 +0100170}
171
pineafan63fc5e22022-08-04 22:04:10 +0100172export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100173 try {
Skyler Grey0d885222023-03-08 21:46:37 +0000174 return (await testMalware(element)).malware;
pineafan813bdf42022-07-24 10:39:10 +0100175 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100176 return true;
pineafan813bdf42022-07-24 10:39:10 +0100177 }
178}
179
pineafan1e462ab2023-03-07 21:34:06 +0000180export function TestString(
181 string: string,
182 soft: string[],
183 strict: string[],
184 enabled?: boolean
185): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000186 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100187 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100188 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100189 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100190 }
191 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100192 for (const word of soft) {
193 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100194 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000195 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100196 }
197 }
198 }
pineafan63fc5e22022-08-04 22:04:10 +0100199 return null;
pineafan813bdf42022-07-24 10:39:10 +0100200}
201
pineafan63fc5e22022-08-04 22:04:10 +0100202export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100203 const text = await Tesseract.recognize(url, {
204 lang: "eng",
205 oem: 1,
206 psm: 3
207 });
Skyler Greye9c3ef62023-03-09 14:09:00 +0000208 console.log(text);
pineafan813bdf42022-07-24 10:39:10 +0100209 return text;
210}
pineafan6de4da52023-03-07 20:43:44 +0000211
Skyler Grey0d885222023-03-08 21:46:37 +0000212export async function doMemberChecks(member: Discord.GuildMember): Promise<void> {
pineafan6de4da52023-03-07 20:43:44 +0000213 if (member.user.bot) return;
Skyler Greyea0937b2023-03-09 00:36:38 +0000214 console.log("Checking member " + member.user.tag);
Skyler Grey0d885222023-03-08 21:46:37 +0000215 const guild = member.guild;
pineafan6de4da52023-03-07 20:43:44 +0000216 const guildData = await client.database.guilds.read(guild.id);
217 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000218 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
Skyler Greyea0937b2023-03-09 00:36:38 +0000219 console.log(1, loose, strict);
pineafan6de4da52023-03-07 20:43:44 +0000220 // Does the username contain filtered words
221 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000222 console.log(2, usernameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000223 // Does the nickname contain filtered words
224 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000225 console.log(3, nicknameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000226 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000227 const avatarTextCheck = TestString(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000228 (await TestImage(member.displayAvatarURL({ forceStatic: true }))) ?? "",
pineafan1e462ab2023-03-07 21:34:06 +0000229 loose,
230 strict,
231 guildData.filters.wordFilter.enabled
232 );
Skyler Greyea0937b2023-03-09 00:36:38 +0000233 console.log(4, avatarTextCheck);
pineafan6de4da52023-03-07 20:43:44 +0000234 // Is the profile picture NSFW
Skyler Grey0d885222023-03-08 21:46:37 +0000235 const avatar = member.displayAvatarURL({ extension: "png", size: 1024, forceStatic: true });
Skyler Grey74169642023-03-09 11:59:09 +0000236 const avatarCheck = guildData.filters.images.NSFW && (await NSFWCheck(avatar));
Skyler Greyea0937b2023-03-09 00:36:38 +0000237 console.log(5, avatarCheck);
pineafan6de4da52023-03-07 20:43:44 +0000238 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000239 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
Skyler Greyea0937b2023-03-09 00:36:38 +0000240 console.log(6, inviteCheck);
pineafan6de4da52023-03-07 20:43:44 +0000241 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000242 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000243 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
Skyler Greyea0937b2023-03-09 00:36:38 +0000244 console.log(7, nicknameInviteCheck);
pineafan1e462ab2023-03-07 21:34:06 +0000245 if (
246 usernameCheck !== null ||
247 nicknameCheck !== null ||
248 avatarCheck ||
249 inviteCheck ||
250 nicknameInviteCheck ||
251 avatarTextCheck !== null
252 ) {
pineafan6de4da52023-03-07 20:43:44 +0000253 const infractions = [];
254 if (usernameCheck !== null) {
255 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000256 }
257 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000258 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000259 }
260 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000261 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000262 }
263 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000264 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000265 }
266 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000267 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000268 }
269 if (avatarTextCheck !== null) {
270 infractions.push(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000271 `Profile picture contains a ${avatarTextCheck.type}ly filtered word (${avatarTextCheck.word})`
pineafan1e462ab2023-03-07 21:34:06 +0000272 );
pineafan6de4da52023-03-07 20:43:44 +0000273 }
274 if (infractions.length === 0) return;
275 // This is bad - Warn in the staff notifications channel
276 const filter = getEmojiByName("ICONS.FILTER");
277 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
278 const embed = new EmojiEmbed()
279 .setTitle("Member Flagged")
280 .setEmoji("ICONS.FLAGS.RED")
281 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000282 .setDescription(
283 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
284 infractions.map((element) => `${filter} ${element}`).join("\n")
285 );
pineafan6de4da52023-03-07 20:43:44 +0000286 await channel.send({
287 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000288 components: [
289 new ActionRowBuilder<ButtonBuilder>().addComponents(
290 ...[
291 new ButtonBuilder()
292 .setCustomId(`mod:warn:${member.user.id}`)
293 .setLabel("Warn")
294 .setStyle(ButtonStyle.Primary),
295 new ButtonBuilder()
296 .setCustomId(`mod:mute:${member.user.id}`)
297 .setLabel("Mute")
298 .setStyle(ButtonStyle.Primary),
299 new ButtonBuilder()
300 .setCustomId(`mod:kick:${member.user.id}`)
301 .setLabel("Kick")
302 .setStyle(ButtonStyle.Danger),
303 new ButtonBuilder()
304 .setCustomId(`mod:ban:${member.user.id}`)
305 .setLabel("Ban")
306 .setStyle(ButtonStyle.Danger)
307 ].concat(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000308 usernameCheck !== null || nicknameCheck !== null
pineafan1e462ab2023-03-07 21:34:06 +0000309 ? [
310 new ButtonBuilder()
311 .setCustomId(`mod:nickname:${member.user.id}`)
312 .setLabel("Change Name")
313 .setStyle(ButtonStyle.Primary)
314 ]
315 : []
316 )
317 )
318 ]
pineafan6de4da52023-03-07 20:43:44 +0000319 });
320 }
pineafan1e462ab2023-03-07 21:34:06 +0000321}