blob: 49b203b3dee223c1e295da7cd4c68b8a54e81e02 [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";
pineafan813bdf42022-07-24 10:39:10 +010014
Skyler Grey75ea9172022-08-06 10:22:23 +010015interface NSFWSchema {
16 nsfw: boolean;
TheCodedProf5b53a8c2023-02-03 15:40:26 -050017 errored?: boolean;
Skyler Grey75ea9172022-08-06 10:22:23 +010018}
19interface MalwareSchema {
20 safe: boolean;
TheCodedProf5b53a8c2023-02-03 15:40:26 -050021 errored?: boolean;
Skyler Grey75ea9172022-08-06 10:22:23 +010022}
pineafan813bdf42022-07-24 10:39:10 +010023
Skyler Grey14432712023-03-07 23:40:50 +000024const nsfw_model = await nsfwjs.load();
Skyler Grey0a4846c2023-03-08 00:32:01 +000025const clamscanner = await new ClamScan().init({});
TheCodedProfd8ef1f32023-03-06 19:15:18 -050026
pineafan02ba0232022-07-24 22:16:15 +010027export async function testNSFW(link: string): Promise<NSFWSchema> {
Skyler Grey14432712023-03-07 23:40:50 +000028 const [fileStream, hash] = await streamAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000029 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey14432712023-03-07 23:40:50 +000030 if (alreadyHaveCheck?.nsfw) return { nsfw: alreadyHaveCheck.nsfw };
TheCodedProfd8ef1f32023-03-06 19:15:18 -050031
Skyler Grey32179982023-03-07 23:59:06 +000032 const image = tf.tensor3d(new Uint8Array(fileStream));
TheCodedProfd8ef1f32023-03-06 19:15:18 -050033
Skyler Grey14432712023-03-07 23:40:50 +000034 const predictions = (await nsfw_model.classify(image, 1))[0]!;
35 image.dispose();
TheCodedProfd8ef1f32023-03-06 19:15:18 -050036
Skyler Grey14432712023-03-07 23:40:50 +000037 return { nsfw: predictions.className === "Hentai" || predictions.className === "Porn" };
pineafan813bdf42022-07-24 10:39:10 +010038}
39
pineafan02ba0232022-07-24 22:16:15 +010040export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey0a4846c2023-03-08 00:32:01 +000041 const [fileName, hash] = await saveAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000042 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey14432712023-03-07 23:40:50 +000043 if (alreadyHaveCheck?.malware) return { safe: alreadyHaveCheck.malware };
Skyler Grey0a4846c2023-03-08 00:32:01 +000044 let safe;
45 try {
46 safe = !(await clamscanner.scanFile(fileName)).isInfected;
47 } catch (e) {
48 return { safe: true };
49 }
50 client.database.scanCache.write(hash, "malware", safe);
51 return { safe };
pineafan3a02ea32022-08-11 21:35:04 +010052}
53
54export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000055 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey14432712023-03-07 23:40:50 +000056 if (alreadyHaveCheck?.bad_link) return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags };
TheCodedProfb5e9d552023-01-29 15:43:26 -050057 const scanned: { safe?: boolean; tags?: string[] } = await fetch("https://unscan.p.rapidapi.com/link", {
pineafan3a02ea32022-08-11 21:35:04 +010058 method: "POST",
59 headers: {
60 "X-RapidAPI-Key": client.config.rapidApiKey,
61 "X-RapidAPI-Host": "unscan.p.rapidapi.com"
62 },
63 body: `{"link":"${link}"}`
64 })
65 .then((response) => response.json() as Promise<MalwareSchema>)
66 .catch((err) => {
67 console.error(err);
68 return { safe: true, tags: [] };
69 });
Skyler Grey14432712023-03-07 23:40:50 +000070 client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
pineafan3a02ea32022-08-11 21:35:04 +010071 return {
72 safe: scanned.safe ?? true,
73 tags: scanned.tags ?? []
74 };
pineafan813bdf42022-07-24 10:39:10 +010075}
76
Skyler Grey14432712023-03-07 23:40:50 +000077export async function streamAttachment(link: string): Promise<[ArrayBuffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000078 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey32179982023-03-07 23:59:06 +000079 const enc = new TextDecoder("utf-8");
80 return [image, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
81}
82
83export async function saveAttachment(link: string): Promise<[string, string]> {
84 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey75ea9172022-08-06 10:22:23 +010085 const fileName = generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -050086 const enc = new TextDecoder("utf-8");
87 writeFileSync(fileName, new DataView(image), "base64");
Skyler Grey32179982023-03-07 23:59:06 +000088 return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +010089}
90
pineafan813bdf42022-07-24 10:39:10 +010091const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +010092 PHISHING: "Links designed to trick users into clicking on them.",
93 DATING: "Dating sites.",
94 TRACKERS: "Websites that store or track personal information.",
95 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +010096 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +010097 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 +010098 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +010099 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100100 PORN: "Websites that include pornography.",
101 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100102 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100103 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100104 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 +0100105 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
106 SCAMS: "Sites which are designed to trick you into doing something.",
107 TORRENT: "Websites that download torrent files.",
108 HATE: "Websites that spread hate towards groups or individuals.",
109 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100110};
pineafan813bdf42022-07-24 10:39:10 +0100111export { linkTypes };
112
pineafan63fc5e22022-08-04 22:04:10 +0100113export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100114 const links =
115 message.content.match(
116 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
117 ) ?? [];
118 const detections: { tags: string[]; safe: boolean }[] = [];
119 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100120 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100121 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100122 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 +0100123 returned = await testLink(element);
124 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100125 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100126 return;
127 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100128 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100129 });
130 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100131 const detectionsTypes = detections
132 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100133 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100134 if (type) return type;
135 // if (!element.safe) return "UNSAFE"
136 return undefined;
137 })
138 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100139 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100140}
141
pineafan63fc5e22022-08-04 22:04:10 +0100142export async function NSFWCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100143 try {
TheCodedProfb5e9d552023-01-29 15:43:26 -0500144 return (await testNSFW(element)).nsfw;
pineafan813bdf42022-07-24 10:39:10 +0100145 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100146 return false;
pineafan813bdf42022-07-24 10:39:10 +0100147 }
148}
149
Skyler Grey11236ba2022-08-08 21:13:33 +0100150export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100151 if (element.height === null || element.width === null) return true;
152 if (element.height < 20 || element.width < 20) return false;
153 return true;
pineafan813bdf42022-07-24 10:39:10 +0100154}
155
pineafan63fc5e22022-08-04 22:04:10 +0100156export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100157 try {
pineafan63fc5e22022-08-04 22:04:10 +0100158 return (await testMalware(element)).safe;
pineafan813bdf42022-07-24 10:39:10 +0100159 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100160 return true;
pineafan813bdf42022-07-24 10:39:10 +0100161 }
162}
163
pineafan1e462ab2023-03-07 21:34:06 +0000164export function TestString(
165 string: string,
166 soft: string[],
167 strict: string[],
168 enabled?: boolean
169): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000170 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100171 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100172 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100173 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100174 }
175 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100176 for (const word of soft) {
177 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100178 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000179 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100180 }
181 }
182 }
pineafan63fc5e22022-08-04 22:04:10 +0100183 return null;
pineafan813bdf42022-07-24 10:39:10 +0100184}
185
pineafan63fc5e22022-08-04 22:04:10 +0100186export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100187 const text = await Tesseract.recognize(url, {
188 lang: "eng",
189 oem: 1,
190 psm: 3
191 });
pineafan813bdf42022-07-24 10:39:10 +0100192 return text;
193}
pineafan6de4da52023-03-07 20:43:44 +0000194
195export async function doMemberChecks(member: Discord.GuildMember, guild: Discord.Guild): Promise<void> {
196 if (member.user.bot) return;
197 const guildData = await client.database.guilds.read(guild.id);
198 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000199 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
pineafan6de4da52023-03-07 20:43:44 +0000200 // Does the username contain filtered words
201 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
202 // Does the nickname contain filtered words
203 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
204 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000205 const avatarTextCheck = TestString(
206 (await TestImage(member.user.displayAvatarURL({ forceStatic: true }))) ?? "",
207 loose,
208 strict,
209 guildData.filters.wordFilter.enabled
210 );
pineafan6de4da52023-03-07 20:43:44 +0000211 // Is the profile picture NSFW
pineafan1e462ab2023-03-07 21:34:06 +0000212 const avatarCheck =
213 guildData.filters.images.NSFW && (await NSFWCheck(member.user.displayAvatarURL({ forceStatic: true })));
pineafan6de4da52023-03-07 20:43:44 +0000214 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000215 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
pineafan6de4da52023-03-07 20:43:44 +0000216 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000217 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000218 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
pineafan6de4da52023-03-07 20:43:44 +0000219
pineafan1e462ab2023-03-07 21:34:06 +0000220 if (
221 usernameCheck !== null ||
222 nicknameCheck !== null ||
223 avatarCheck ||
224 inviteCheck ||
225 nicknameInviteCheck ||
226 avatarTextCheck !== null
227 ) {
pineafan6de4da52023-03-07 20:43:44 +0000228 const infractions = [];
229 if (usernameCheck !== null) {
230 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000231 }
232 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000233 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000234 }
235 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000236 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000237 }
238 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000239 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000240 }
241 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000242 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000243 }
244 if (avatarTextCheck !== null) {
245 infractions.push(
246 `Profile picture contains a ${avatarTextCheck.type}ly filtered word: ${avatarTextCheck.word}`
247 );
pineafan6de4da52023-03-07 20:43:44 +0000248 }
249 if (infractions.length === 0) return;
250 // This is bad - Warn in the staff notifications channel
251 const filter = getEmojiByName("ICONS.FILTER");
252 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
253 const embed = new EmojiEmbed()
254 .setTitle("Member Flagged")
255 .setEmoji("ICONS.FLAGS.RED")
256 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000257 .setDescription(
258 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
259 infractions.map((element) => `${filter} ${element}`).join("\n")
260 );
pineafan6de4da52023-03-07 20:43:44 +0000261 await channel.send({
262 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000263 components: [
264 new ActionRowBuilder<ButtonBuilder>().addComponents(
265 ...[
266 new ButtonBuilder()
267 .setCustomId(`mod:warn:${member.user.id}`)
268 .setLabel("Warn")
269 .setStyle(ButtonStyle.Primary),
270 new ButtonBuilder()
271 .setCustomId(`mod:mute:${member.user.id}`)
272 .setLabel("Mute")
273 .setStyle(ButtonStyle.Primary),
274 new ButtonBuilder()
275 .setCustomId(`mod:kick:${member.user.id}`)
276 .setLabel("Kick")
277 .setStyle(ButtonStyle.Danger),
278 new ButtonBuilder()
279 .setCustomId(`mod:ban:${member.user.id}`)
280 .setLabel("Ban")
281 .setStyle(ButtonStyle.Danger)
282 ].concat(
283 usernameCheck !== null || nicknameCheck !== null || avatarTextCheck !== null
284 ? [
285 new ButtonBuilder()
286 .setCustomId(`mod:nickname:${member.user.id}`)
287 .setLabel("Change Name")
288 .setStyle(ButtonStyle.Primary)
289 ]
290 : []
291 )
292 )
293 ]
pineafan6de4da52023-03-07 20:43:44 +0000294 });
295 }
pineafan1e462ab2023-03-07 21:34:06 +0000296}