blob: 80ca150fa867196deb5d668e3e636e43c60792b2 [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 Greyea0937b2023-03-09 00:36:38 +0000213 console.log("Checking member " + member.user.tag);
Skyler Grey0d885222023-03-08 21:46:37 +0000214 const guild = member.guild;
pineafan6de4da52023-03-07 20:43:44 +0000215 const guildData = await client.database.guilds.read(guild.id);
216 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000217 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
Skyler Greyea0937b2023-03-09 00:36:38 +0000218 console.log(1, loose, strict);
pineafan6de4da52023-03-07 20:43:44 +0000219 // Does the username contain filtered words
220 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000221 console.log(2, usernameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000222 // Does the nickname contain filtered words
223 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000224 console.log(3, nicknameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000225 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000226 const avatarTextCheck = TestString(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000227 (await TestImage(member.displayAvatarURL({ forceStatic: true }))) ?? "",
pineafan1e462ab2023-03-07 21:34:06 +0000228 loose,
229 strict,
230 guildData.filters.wordFilter.enabled
231 );
Skyler Greyea0937b2023-03-09 00:36:38 +0000232 console.log(4, avatarTextCheck);
pineafan6de4da52023-03-07 20:43:44 +0000233 // Is the profile picture NSFW
Skyler Grey0d885222023-03-08 21:46:37 +0000234 const avatar = member.displayAvatarURL({ extension: "png", size: 1024, forceStatic: true });
Skyler Grey74169642023-03-09 11:59:09 +0000235 const avatarCheck = guildData.filters.images.NSFW && (await NSFWCheck(avatar));
Skyler Greyea0937b2023-03-09 00:36:38 +0000236 console.log(5, avatarCheck);
pineafan6de4da52023-03-07 20:43:44 +0000237 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000238 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
Skyler Greyea0937b2023-03-09 00:36:38 +0000239 console.log(6, inviteCheck);
pineafan6de4da52023-03-07 20:43:44 +0000240 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000241 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000242 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
Skyler Greyea0937b2023-03-09 00:36:38 +0000243 console.log(7, nicknameInviteCheck);
pineafan1e462ab2023-03-07 21:34:06 +0000244 if (
245 usernameCheck !== null ||
246 nicknameCheck !== null ||
247 avatarCheck ||
248 inviteCheck ||
249 nicknameInviteCheck ||
250 avatarTextCheck !== null
251 ) {
pineafan6de4da52023-03-07 20:43:44 +0000252 const infractions = [];
253 if (usernameCheck !== null) {
254 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000255 }
256 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000257 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000258 }
259 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000260 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000261 }
262 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000263 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000264 }
265 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000266 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000267 }
268 if (avatarTextCheck !== null) {
269 infractions.push(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000270 `Profile picture contains a ${avatarTextCheck.type}ly filtered word (${avatarTextCheck.word})`
pineafan1e462ab2023-03-07 21:34:06 +0000271 );
pineafan6de4da52023-03-07 20:43:44 +0000272 }
273 if (infractions.length === 0) return;
274 // This is bad - Warn in the staff notifications channel
275 const filter = getEmojiByName("ICONS.FILTER");
276 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
277 const embed = new EmojiEmbed()
278 .setTitle("Member Flagged")
279 .setEmoji("ICONS.FLAGS.RED")
280 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000281 .setDescription(
282 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
283 infractions.map((element) => `${filter} ${element}`).join("\n")
284 );
pineafan6de4da52023-03-07 20:43:44 +0000285 await channel.send({
286 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000287 components: [
288 new ActionRowBuilder<ButtonBuilder>().addComponents(
289 ...[
290 new ButtonBuilder()
291 .setCustomId(`mod:warn:${member.user.id}`)
292 .setLabel("Warn")
293 .setStyle(ButtonStyle.Primary),
294 new ButtonBuilder()
295 .setCustomId(`mod:mute:${member.user.id}`)
296 .setLabel("Mute")
297 .setStyle(ButtonStyle.Primary),
298 new ButtonBuilder()
299 .setCustomId(`mod:kick:${member.user.id}`)
300 .setLabel("Kick")
301 .setStyle(ButtonStyle.Danger),
302 new ButtonBuilder()
303 .setCustomId(`mod:ban:${member.user.id}`)
304 .setLabel("Ban")
305 .setStyle(ButtonStyle.Danger)
306 ].concat(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000307 usernameCheck !== null || nicknameCheck !== null
pineafan1e462ab2023-03-07 21:34:06 +0000308 ? [
309 new ButtonBuilder()
310 .setCustomId(`mod:nickname:${member.user.id}`)
311 .setLabel("Change Name")
312 .setStyle(ButtonStyle.Primary)
313 ]
314 : []
315 )
316 )
317 ]
pineafan6de4da52023-03-07 20:43:44 +0000318 });
319 }
pineafan1e462ab2023-03-07 21:34:06 +0000320}