blob: 93af960b66bdfac47202f8c07d1704d77f603388 [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 Grey8034b942023-03-09 00:34:46 +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 Grey0d885222023-03-08 21:46:37 +000040 if (alreadyHaveCheck && ("nsfw" in alreadyHaveCheck!)) {
41 return { nsfw: alreadyHaveCheck.nsfw }
42 };
TheCodedProfd8ef1f32023-03-06 19:15:18 -050043
Skyler Grey8034b942023-03-09 00:34:46 +000044 const converted = await new Promise((resolve, reject) => gm(fileStream).command("convert").toBuffer("PNG", (err, buf) => {
45 if (err) return reject(err);
46 resolve(buf);
47 })) as Buffer;
48 const array = new Uint8Array(converted);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050049
Skyler Grey0d885222023-03-08 21:46:37 +000050 const img = tf.node.decodeImage(array) as tf.Tensor3D;
51
52 const predictions = (await nsfw_model.classify(img, 1))[0]!;
53 console.log(2, predictions);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050054
Skyler Greyd1157312023-03-08 10:07:38 +000055 const nsfw = predictions.className === "Hentai" || predictions.className === "Porn";
56 await client.database.scanCache.write(hash, "nsfw", nsfw);
57
58 return { nsfw };
pineafan813bdf42022-07-24 10:39:10 +010059}
60
pineafan02ba0232022-07-24 22:16:15 +010061export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey0a4846c2023-03-08 00:32:01 +000062 const [fileName, hash] = await saveAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000063 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey0d885222023-03-08 21:46:37 +000064 if (alreadyHaveCheck?.malware !== undefined) return { malware: alreadyHaveCheck.malware };
Skyler Greyd1157312023-03-08 10:07:38 +000065 let malware;
Skyler Grey0a4846c2023-03-08 00:32:01 +000066 try {
Skyler Greyd1157312023-03-08 10:07:38 +000067 malware = (await clamscanner.scanFile(fileName)).isInfected;
Skyler Grey0a4846c2023-03-08 00:32:01 +000068 } catch (e) {
Skyler Grey0d885222023-03-08 21:46:37 +000069 return { malware: true };
Skyler Grey0a4846c2023-03-08 00:32:01 +000070 }
Skyler Greyf4f21c42023-03-08 14:36:29 +000071 await client.database.scanCache.write(hash, "malware", malware);
Skyler Grey0d885222023-03-08 21:46:37 +000072 return { malware };
pineafan3a02ea32022-08-11 21:35:04 +010073}
74
75export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000076 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey0d885222023-03-08 21:46:37 +000077 if (alreadyHaveCheck?.bad_link !== undefined)
78 return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags ?? [] };
79 return { safe: true, tags: [] };
80 // const scanned: { safe?: boolean; tags?: string[] } = {}
81 // await client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
82 // return {
83 // safe: scanned.safe ?? true,
84 // tags: scanned.tags ?? []
85 // };
pineafan813bdf42022-07-24 10:39:10 +010086}
87
Skyler Grey0d885222023-03-08 21:46:37 +000088export async function streamAttachment(link: string): Promise<[Buffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000089 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey32179982023-03-07 23:59:06 +000090 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +000091 const buf = Buffer.from(image);
92 return [buf, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
Skyler Grey32179982023-03-07 23:59:06 +000093}
94
95export async function saveAttachment(link: string): Promise<[string, string]> {
96 const image = await (await fetch(link)).arrayBuffer();
Skyler Greyf4f21c42023-03-08 14:36:29 +000097 const fileName = await generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -050098 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +000099 writeFileSync(fileName, new DataView(image));
Skyler Grey32179982023-03-07 23:59:06 +0000100 return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +0100101}
102
pineafan813bdf42022-07-24 10:39:10 +0100103const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +0100104 PHISHING: "Links designed to trick users into clicking on them.",
105 DATING: "Dating sites.",
106 TRACKERS: "Websites that store or track personal information.",
107 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100108 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +0100109 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 +0100110 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100111 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100112 PORN: "Websites that include pornography.",
113 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100114 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100115 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100116 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 +0100117 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
118 SCAMS: "Sites which are designed to trick you into doing something.",
119 TORRENT: "Websites that download torrent files.",
120 HATE: "Websites that spread hate towards groups or individuals.",
121 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100122};
pineafan813bdf42022-07-24 10:39:10 +0100123export { linkTypes };
124
pineafan63fc5e22022-08-04 22:04:10 +0100125export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100126 const links =
127 message.content.match(
128 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
129 ) ?? [];
130 const detections: { tags: string[]; safe: boolean }[] = [];
131 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100132 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100133 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100134 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 +0100135 returned = await testLink(element);
136 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100137 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100138 return;
139 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100140 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100141 });
142 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100143 const detectionsTypes = detections
144 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100145 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100146 if (type) return type;
147 // if (!element.safe) return "UNSAFE"
148 return undefined;
149 })
150 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100151 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100152}
153
Skyler Grey0d885222023-03-08 21:46:37 +0000154export async function NSFWCheck(element: {
155 url: string;
Skyler Grey0d885222023-03-08 21:46:37 +0000156 height: number | null;
157 width: number | null;
158}): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100159 try {
TheCodedProfb5e9d552023-01-29 15:43:26 -0500160 return (await testNSFW(element)).nsfw;
Skyler Grey0d885222023-03-08 21:46:37 +0000161 } catch (e) {
162 console.log(e)
pineafan63fc5e22022-08-04 22:04:10 +0100163 return false;
pineafan813bdf42022-07-24 10:39:10 +0100164 }
165}
166
Skyler Grey11236ba2022-08-08 21:13:33 +0100167export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100168 if (element.height === null || element.width === null) return true;
169 if (element.height < 20 || element.width < 20) return false;
170 return true;
pineafan813bdf42022-07-24 10:39:10 +0100171}
172
pineafan63fc5e22022-08-04 22:04:10 +0100173export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100174 try {
Skyler Grey0d885222023-03-08 21:46:37 +0000175 return (await testMalware(element)).malware;
pineafan813bdf42022-07-24 10:39:10 +0100176 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100177 return true;
pineafan813bdf42022-07-24 10:39:10 +0100178 }
179}
180
pineafan1e462ab2023-03-07 21:34:06 +0000181export function TestString(
182 string: string,
183 soft: string[],
184 strict: string[],
185 enabled?: boolean
186): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000187 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100188 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100189 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100190 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100191 }
192 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100193 for (const word of soft) {
194 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100195 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000196 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100197 }
198 }
199 }
pineafan63fc5e22022-08-04 22:04:10 +0100200 return null;
pineafan813bdf42022-07-24 10:39:10 +0100201}
202
pineafan63fc5e22022-08-04 22:04:10 +0100203export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100204 const text = await Tesseract.recognize(url, {
205 lang: "eng",
206 oem: 1,
207 psm: 3
208 });
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 Grey0d885222023-03-08 21:46:37 +0000214 console.log("Checking member " + member.user.tag)
215 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 Grey0d885222023-03-08 21:46:37 +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 Grey0d885222023-03-08 21:46:37 +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 Grey0d885222023-03-08 21:46:37 +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(
228 (await TestImage(member.user.displayAvatarURL({ forceStatic: true }))) ?? "",
229 loose,
230 strict,
231 guildData.filters.wordFilter.enabled
232 );
Skyler Grey0d885222023-03-08 21:46:37 +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 });
pineafan1e462ab2023-03-07 21:34:06 +0000236 const avatarCheck =
Skyler Grey8034b942023-03-09 00:34:46 +0000237 guildData.filters.images.NSFW && (await NSFWCheck({url: avatar, height: 1024, width: 1024}));
Skyler Grey0d885222023-03-08 21:46:37 +0000238 console.log(5, avatarCheck)
pineafan6de4da52023-03-07 20:43:44 +0000239 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000240 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
Skyler Grey0d885222023-03-08 21:46:37 +0000241 console.log(6, inviteCheck)
pineafan6de4da52023-03-07 20:43:44 +0000242 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000243 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000244 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
Skyler Grey0d885222023-03-08 21:46:37 +0000245 console.log(7, nicknameInviteCheck)
pineafan1e462ab2023-03-07 21:34:06 +0000246 if (
247 usernameCheck !== null ||
248 nicknameCheck !== null ||
249 avatarCheck ||
250 inviteCheck ||
251 nicknameInviteCheck ||
252 avatarTextCheck !== null
253 ) {
pineafan6de4da52023-03-07 20:43:44 +0000254 const infractions = [];
255 if (usernameCheck !== null) {
256 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000257 }
258 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000259 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000260 }
261 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000262 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000263 }
264 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000265 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000266 }
267 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000268 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000269 }
270 if (avatarTextCheck !== null) {
271 infractions.push(
272 `Profile picture contains a ${avatarTextCheck.type}ly filtered word: ${avatarTextCheck.word}`
273 );
pineafan6de4da52023-03-07 20:43:44 +0000274 }
275 if (infractions.length === 0) return;
276 // This is bad - Warn in the staff notifications channel
277 const filter = getEmojiByName("ICONS.FILTER");
278 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
279 const embed = new EmojiEmbed()
280 .setTitle("Member Flagged")
281 .setEmoji("ICONS.FLAGS.RED")
282 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000283 .setDescription(
284 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
285 infractions.map((element) => `${filter} ${element}`).join("\n")
286 );
pineafan6de4da52023-03-07 20:43:44 +0000287 await channel.send({
288 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000289 components: [
290 new ActionRowBuilder<ButtonBuilder>().addComponents(
291 ...[
292 new ButtonBuilder()
293 .setCustomId(`mod:warn:${member.user.id}`)
294 .setLabel("Warn")
295 .setStyle(ButtonStyle.Primary),
296 new ButtonBuilder()
297 .setCustomId(`mod:mute:${member.user.id}`)
298 .setLabel("Mute")
299 .setStyle(ButtonStyle.Primary),
300 new ButtonBuilder()
301 .setCustomId(`mod:kick:${member.user.id}`)
302 .setLabel("Kick")
303 .setStyle(ButtonStyle.Danger),
304 new ButtonBuilder()
305 .setCustomId(`mod:ban:${member.user.id}`)
306 .setLabel("Ban")
307 .setStyle(ButtonStyle.Danger)
308 ].concat(
309 usernameCheck !== null || nicknameCheck !== null || avatarTextCheck !== null
310 ? [
311 new ButtonBuilder()
312 .setCustomId(`mod:nickname:${member.user.id}`)
313 .setLabel("Change Name")
314 .setStyle(ButtonStyle.Primary)
315 ]
316 : []
317 )
318 )
319 ]
pineafan6de4da52023-03-07 20:43:44 +0000320 });
321 }
pineafan1e462ab2023-03-07 21:34:06 +0000322}