blob: 74887d271896433ceaa67b67d0a77b8cb0ddbe51 [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 Grey14432712023-03-07 23:40:50 +000026const nsfw_model = await nsfwjs.load();
Skyler Greyd1157312023-03-08 10:07:38 +000027const clamscanner = await new ClamScan().init({
28 clamdscan: {
29 socket: config.clamavSocket
30 }
31});
TheCodedProfd8ef1f32023-03-06 19:15:18 -050032
Skyler Grey0d885222023-03-08 21:46:37 +000033export async function testNSFW(attachment: {
34 url: string;
Skyler Grey0d885222023-03-08 21:46:37 +000035 height: number | null;
36 width: number | null;
37}): Promise<NSFWSchema> {
38 const [fileStream, hash] = await streamAttachment(attachment.url);
Skyler Greyda16adf2023-03-05 10:22:12 +000039 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Greyea0937b2023-03-09 00:36:38 +000040 if (alreadyHaveCheck && "nsfw" in alreadyHaveCheck!) {
41 return { nsfw: alreadyHaveCheck.nsfw };
42 }
TheCodedProfd8ef1f32023-03-06 19:15:18 -050043
Skyler Greyea0937b2023-03-09 00:36:38 +000044 const converted = (await new Promise((resolve, reject) =>
45 gm(fileStream)
46 .command("convert")
47 .toBuffer("PNG", (err, buf) => {
48 if (err) return reject(err);
49 resolve(buf);
50 })
51 )) as Buffer;
Skyler Grey8034b942023-03-09 00:34:46 +000052 const array = new Uint8Array(converted);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050053
Skyler Grey0d885222023-03-08 21:46:37 +000054 const img = tf.node.decodeImage(array) as tf.Tensor3D;
55
56 const predictions = (await nsfw_model.classify(img, 1))[0]!;
57 console.log(2, predictions);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050058
Skyler Greyd1157312023-03-08 10:07:38 +000059 const nsfw = predictions.className === "Hentai" || predictions.className === "Porn";
60 await client.database.scanCache.write(hash, "nsfw", nsfw);
61
62 return { nsfw };
pineafan813bdf42022-07-24 10:39:10 +010063}
64
pineafan02ba0232022-07-24 22:16:15 +010065export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey0a4846c2023-03-08 00:32:01 +000066 const [fileName, hash] = await saveAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000067 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey0d885222023-03-08 21:46:37 +000068 if (alreadyHaveCheck?.malware !== undefined) return { malware: alreadyHaveCheck.malware };
Skyler Greyd1157312023-03-08 10:07:38 +000069 let malware;
Skyler Grey0a4846c2023-03-08 00:32:01 +000070 try {
Skyler Greyd1157312023-03-08 10:07:38 +000071 malware = (await clamscanner.scanFile(fileName)).isInfected;
Skyler Grey0a4846c2023-03-08 00:32:01 +000072 } catch (e) {
Skyler Grey0d885222023-03-08 21:46:37 +000073 return { malware: true };
Skyler Grey0a4846c2023-03-08 00:32:01 +000074 }
Skyler Greyf4f21c42023-03-08 14:36:29 +000075 await client.database.scanCache.write(hash, "malware", malware);
Skyler Grey0d885222023-03-08 21:46:37 +000076 return { malware };
pineafan3a02ea32022-08-11 21:35:04 +010077}
78
79export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000080 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey0d885222023-03-08 21:46:37 +000081 if (alreadyHaveCheck?.bad_link !== undefined)
82 return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags ?? [] };
83 return { safe: true, tags: [] };
84 // const scanned: { safe?: boolean; tags?: string[] } = {}
85 // await client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
86 // return {
87 // safe: scanned.safe ?? true,
88 // tags: scanned.tags ?? []
89 // };
pineafan813bdf42022-07-24 10:39:10 +010090}
91
Skyler Grey0d885222023-03-08 21:46:37 +000092export async function streamAttachment(link: string): Promise<[Buffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000093 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey32179982023-03-07 23:59:06 +000094 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +000095 const buf = Buffer.from(image);
96 return [buf, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
Skyler Grey32179982023-03-07 23:59:06 +000097}
98
99export async function saveAttachment(link: string): Promise<[string, string]> {
100 const image = await (await fetch(link)).arrayBuffer();
Skyler Greyf4f21c42023-03-08 14:36:29 +0000101 const fileName = await generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -0500102 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +0000103 writeFileSync(fileName, new DataView(image));
Skyler Grey32179982023-03-07 23:59:06 +0000104 return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +0100105}
106
pineafan813bdf42022-07-24 10:39:10 +0100107const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +0100108 PHISHING: "Links designed to trick users into clicking on them.",
109 DATING: "Dating sites.",
110 TRACKERS: "Websites that store or track personal information.",
111 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100112 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +0100113 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 +0100114 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100115 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100116 PORN: "Websites that include pornography.",
117 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100118 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100119 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100120 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 +0100121 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
122 SCAMS: "Sites which are designed to trick you into doing something.",
123 TORRENT: "Websites that download torrent files.",
124 HATE: "Websites that spread hate towards groups or individuals.",
125 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100126};
pineafan813bdf42022-07-24 10:39:10 +0100127export { linkTypes };
128
pineafan63fc5e22022-08-04 22:04:10 +0100129export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100130 const links =
131 message.content.match(
132 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
133 ) ?? [];
134 const detections: { tags: string[]; safe: boolean }[] = [];
135 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100136 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100137 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100138 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 +0100139 returned = await testLink(element);
140 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100141 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100142 return;
143 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100144 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100145 });
146 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100147 const detectionsTypes = detections
148 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100149 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100150 if (type) return type;
151 // if (!element.safe) return "UNSAFE"
152 return undefined;
153 })
154 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100155 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100156}
157
Skyler Grey0d885222023-03-08 21:46:37 +0000158export async function NSFWCheck(element: {
159 url: string;
Skyler Grey0d885222023-03-08 21:46:37 +0000160 height: number | null;
161 width: number | null;
162}): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100163 try {
TheCodedProfb5e9d552023-01-29 15:43:26 -0500164 return (await testNSFW(element)).nsfw;
Skyler Grey0d885222023-03-08 21:46:37 +0000165 } catch (e) {
Skyler Greyea0937b2023-03-09 00:36:38 +0000166 console.log(e);
pineafan63fc5e22022-08-04 22:04:10 +0100167 return false;
pineafan813bdf42022-07-24 10:39:10 +0100168 }
169}
170
Skyler Grey11236ba2022-08-08 21:13:33 +0100171export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100172 if (element.height === null || element.width === null) return true;
173 if (element.height < 20 || element.width < 20) return false;
174 return true;
pineafan813bdf42022-07-24 10:39:10 +0100175}
176
pineafan63fc5e22022-08-04 22:04:10 +0100177export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100178 try {
Skyler Grey0d885222023-03-08 21:46:37 +0000179 return (await testMalware(element)).malware;
pineafan813bdf42022-07-24 10:39:10 +0100180 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100181 return true;
pineafan813bdf42022-07-24 10:39:10 +0100182 }
183}
184
pineafan1e462ab2023-03-07 21:34:06 +0000185export function TestString(
186 string: string,
187 soft: string[],
188 strict: string[],
189 enabled?: boolean
190): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000191 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100192 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100193 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100194 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100195 }
196 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100197 for (const word of soft) {
198 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100199 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000200 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100201 }
202 }
203 }
pineafan63fc5e22022-08-04 22:04:10 +0100204 return null;
pineafan813bdf42022-07-24 10:39:10 +0100205}
206
pineafan63fc5e22022-08-04 22:04:10 +0100207export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100208 const text = await Tesseract.recognize(url, {
209 lang: "eng",
210 oem: 1,
211 psm: 3
212 });
pineafan813bdf42022-07-24 10:39:10 +0100213 return text;
214}
pineafan6de4da52023-03-07 20:43:44 +0000215
Skyler Grey0d885222023-03-08 21:46:37 +0000216export async function doMemberChecks(member: Discord.GuildMember): Promise<void> {
pineafan6de4da52023-03-07 20:43:44 +0000217 if (member.user.bot) return;
Skyler Greyea0937b2023-03-09 00:36:38 +0000218 console.log("Checking member " + member.user.tag);
Skyler Grey0d885222023-03-08 21:46:37 +0000219 const guild = member.guild;
pineafan6de4da52023-03-07 20:43:44 +0000220 const guildData = await client.database.guilds.read(guild.id);
221 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000222 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
Skyler Greyea0937b2023-03-09 00:36:38 +0000223 console.log(1, loose, strict);
pineafan6de4da52023-03-07 20:43:44 +0000224 // Does the username contain filtered words
225 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000226 console.log(2, usernameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000227 // Does the nickname contain filtered words
228 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
Skyler Greyea0937b2023-03-09 00:36:38 +0000229 console.log(3, nicknameCheck);
pineafan6de4da52023-03-07 20:43:44 +0000230 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000231 const avatarTextCheck = TestString(
232 (await TestImage(member.user.displayAvatarURL({ forceStatic: true }))) ?? "",
233 loose,
234 strict,
235 guildData.filters.wordFilter.enabled
236 );
Skyler Greyea0937b2023-03-09 00:36:38 +0000237 console.log(4, avatarTextCheck);
pineafan6de4da52023-03-07 20:43:44 +0000238 // Is the profile picture NSFW
Skyler Grey0d885222023-03-08 21:46:37 +0000239 const avatar = member.displayAvatarURL({ extension: "png", size: 1024, forceStatic: true });
Skyler Greyea0937b2023-03-09 00:36:38 +0000240 const avatarCheck = guildData.filters.images.NSFW && (await NSFWCheck({ url: avatar, height: 1024, width: 1024 }));
241 console.log(5, avatarCheck);
pineafan6de4da52023-03-07 20:43:44 +0000242 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000243 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
Skyler Greyea0937b2023-03-09 00:36:38 +0000244 console.log(6, inviteCheck);
pineafan6de4da52023-03-07 20:43:44 +0000245 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000246 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000247 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
Skyler Greyea0937b2023-03-09 00:36:38 +0000248 console.log(7, nicknameInviteCheck);
pineafan1e462ab2023-03-07 21:34:06 +0000249 if (
250 usernameCheck !== null ||
251 nicknameCheck !== null ||
252 avatarCheck ||
253 inviteCheck ||
254 nicknameInviteCheck ||
255 avatarTextCheck !== null
256 ) {
pineafan6de4da52023-03-07 20:43:44 +0000257 const infractions = [];
258 if (usernameCheck !== null) {
259 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000260 }
261 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000262 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000263 }
264 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000265 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000266 }
267 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000268 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000269 }
270 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000271 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000272 }
273 if (avatarTextCheck !== null) {
274 infractions.push(
275 `Profile picture contains a ${avatarTextCheck.type}ly filtered word: ${avatarTextCheck.word}`
276 );
pineafan6de4da52023-03-07 20:43:44 +0000277 }
278 if (infractions.length === 0) return;
279 // This is bad - Warn in the staff notifications channel
280 const filter = getEmojiByName("ICONS.FILTER");
281 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
282 const embed = new EmojiEmbed()
283 .setTitle("Member Flagged")
284 .setEmoji("ICONS.FLAGS.RED")
285 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000286 .setDescription(
287 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
288 infractions.map((element) => `${filter} ${element}`).join("\n")
289 );
pineafan6de4da52023-03-07 20:43:44 +0000290 await channel.send({
291 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000292 components: [
293 new ActionRowBuilder<ButtonBuilder>().addComponents(
294 ...[
295 new ButtonBuilder()
296 .setCustomId(`mod:warn:${member.user.id}`)
297 .setLabel("Warn")
298 .setStyle(ButtonStyle.Primary),
299 new ButtonBuilder()
300 .setCustomId(`mod:mute:${member.user.id}`)
301 .setLabel("Mute")
302 .setStyle(ButtonStyle.Primary),
303 new ButtonBuilder()
304 .setCustomId(`mod:kick:${member.user.id}`)
305 .setLabel("Kick")
306 .setStyle(ButtonStyle.Danger),
307 new ButtonBuilder()
308 .setCustomId(`mod:ban:${member.user.id}`)
309 .setLabel("Ban")
310 .setStyle(ButtonStyle.Danger)
311 ].concat(
312 usernameCheck !== null || nicknameCheck !== null || avatarTextCheck !== null
313 ? [
314 new ButtonBuilder()
315 .setCustomId(`mod:nickname:${member.user.id}`)
316 .setLabel("Change Name")
317 .setStyle(ButtonStyle.Primary)
318 ]
319 : []
320 )
321 )
322 ]
pineafan6de4da52023-03-07 20:43:44 +0000323 });
324 }
pineafan1e462ab2023-03-07 21:34:06 +0000325}