blob: fb1a436f628391891142b79b2220d0aba562a6bb [file] [log] [blame]
pineafan63fc5e22022-08-04 22:04:10 +01001import fetch from "node-fetch";
TheCodedProfb5e9d552023-01-29 15:43:26 -05002import fs, { writeFileSync, createReadStream } 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 Grey14432712023-03-07 23:40:50 +00008import * as nsfwjs from "nsfwjs/src";
9import * as clamscan from "clamscan";
10import * 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();
TheCodedProfd8ef1f32023-03-06 19:15:18 -050025
pineafan02ba0232022-07-24 22:16:15 +010026export async function testNSFW(link: string): Promise<NSFWSchema> {
Skyler Grey14432712023-03-07 23:40:50 +000027 const [fileStream, hash] = await streamAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000028 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey14432712023-03-07 23:40:50 +000029 if (alreadyHaveCheck?.nsfw) return { nsfw: alreadyHaveCheck.nsfw };
TheCodedProfd8ef1f32023-03-06 19:15:18 -050030
Skyler Grey14432712023-03-07 23:40:50 +000031 const image = tf.node.decodeImage(new Uint8Array(fileStream), 3) as tf.Tensor3D;
TheCodedProfd8ef1f32023-03-06 19:15:18 -050032
Skyler Grey14432712023-03-07 23:40:50 +000033 const predictions = (await nsfw_model.classify(image, 1))[0]!;
34 image.dispose();
TheCodedProfd8ef1f32023-03-06 19:15:18 -050035
Skyler Grey14432712023-03-07 23:40:50 +000036 return { nsfw: predictions.className === "Hentai" || predictions.className === "Porn" };
pineafan813bdf42022-07-24 10:39:10 +010037}
38
pineafan02ba0232022-07-24 22:16:15 +010039export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey14432712023-03-07 23:40:50 +000040 const [p, hash] = await streamAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000041 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey14432712023-03-07 23:40:50 +000042 if (alreadyHaveCheck?.malware) return { safe: alreadyHaveCheck.malware };
43 return { safe: true };
TheCodedProfb5e9d552023-01-29 15:43:26 -050044 const data = new URLSearchParams();
Skyler Grey14432712023-03-07 23:40:50 +000045 // const f = createReadStream(p);
TheCodedProfb5e9d552023-01-29 15:43:26 -050046 data.append("file", f.read(fs.statSync(p).size));
pineafan3a02ea32022-08-11 21:35:04 +010047 const result = await fetch("https://unscan.p.rapidapi.com/malware", {
48 method: "POST",
49 headers: {
50 "X-RapidAPI-Key": client.config.rapidApiKey,
51 "X-RapidAPI-Host": "unscan.p.rapidapi.com"
52 },
53 body: data
54 })
Skyler Greyda16adf2023-03-05 10:22:12 +000055 .then((response) =>
56 response.status === 200 ? (response.json() as Promise<MalwareSchema>) : { safe: true, errored: true }
57 )
pineafan3a02ea32022-08-11 21:35:04 +010058 .catch((err) => {
59 console.error(err);
TheCodedProf5b53a8c2023-02-03 15:40:26 -050060 return { safe: true, errored: true };
pineafan3a02ea32022-08-11 21:35:04 +010061 });
TheCodedProf5b53a8c2023-02-03 15:40:26 -050062 if (!result.errored) {
Skyler Grey14432712023-03-07 23:40:50 +000063 client.database.scanCache.write(hash, "malware", result.safe);
TheCodedProf5b53a8c2023-02-03 15:40:26 -050064 }
pineafan3a02ea32022-08-11 21:35:04 +010065 return { safe: result.safe };
66}
67
68export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000069 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey14432712023-03-07 23:40:50 +000070 if (alreadyHaveCheck?.bad_link) return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags };
TheCodedProfb5e9d552023-01-29 15:43:26 -050071 const scanned: { safe?: boolean; tags?: string[] } = await fetch("https://unscan.p.rapidapi.com/link", {
pineafan3a02ea32022-08-11 21:35:04 +010072 method: "POST",
73 headers: {
74 "X-RapidAPI-Key": client.config.rapidApiKey,
75 "X-RapidAPI-Host": "unscan.p.rapidapi.com"
76 },
77 body: `{"link":"${link}"}`
78 })
79 .then((response) => response.json() as Promise<MalwareSchema>)
80 .catch((err) => {
81 console.error(err);
82 return { safe: true, tags: [] };
83 });
Skyler Grey14432712023-03-07 23:40:50 +000084 client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
pineafan3a02ea32022-08-11 21:35:04 +010085 return {
86 safe: scanned.safe ?? true,
87 tags: scanned.tags ?? []
88 };
pineafan813bdf42022-07-24 10:39:10 +010089}
90
Skyler Grey14432712023-03-07 23:40:50 +000091export async function streamAttachment(link: string): Promise<[ArrayBuffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000092 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey75ea9172022-08-06 10:22:23 +010093 const fileName = generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -050094 const enc = new TextDecoder("utf-8");
95 writeFileSync(fileName, new DataView(image), "base64");
Skyler Grey14432712023-03-07 23:40:50 +000096 return [image, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +010097}
98
pineafan813bdf42022-07-24 10:39:10 +010099const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +0100100 PHISHING: "Links designed to trick users into clicking on them.",
101 DATING: "Dating sites.",
102 TRACKERS: "Websites that store or track personal information.",
103 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100104 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +0100105 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 +0100106 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100107 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100108 PORN: "Websites that include pornography.",
109 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100110 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100111 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100112 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 +0100113 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
114 SCAMS: "Sites which are designed to trick you into doing something.",
115 TORRENT: "Websites that download torrent files.",
116 HATE: "Websites that spread hate towards groups or individuals.",
117 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100118};
pineafan813bdf42022-07-24 10:39:10 +0100119export { linkTypes };
120
pineafan63fc5e22022-08-04 22:04:10 +0100121export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100122 const links =
123 message.content.match(
124 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
125 ) ?? [];
126 const detections: { tags: string[]; safe: boolean }[] = [];
127 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100128 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100129 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100130 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 +0100131 returned = await testLink(element);
132 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100133 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100134 return;
135 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100136 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100137 });
138 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100139 const detectionsTypes = detections
140 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100141 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100142 if (type) return type;
143 // if (!element.safe) return "UNSAFE"
144 return undefined;
145 })
146 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100147 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100148}
149
pineafan63fc5e22022-08-04 22:04:10 +0100150export async function NSFWCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100151 try {
TheCodedProfb5e9d552023-01-29 15:43:26 -0500152 return (await testNSFW(element)).nsfw;
pineafan813bdf42022-07-24 10:39:10 +0100153 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100154 return false;
pineafan813bdf42022-07-24 10:39:10 +0100155 }
156}
157
Skyler Grey11236ba2022-08-08 21:13:33 +0100158export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100159 if (element.height === null || element.width === null) return true;
160 if (element.height < 20 || element.width < 20) return false;
161 return true;
pineafan813bdf42022-07-24 10:39:10 +0100162}
163
pineafan63fc5e22022-08-04 22:04:10 +0100164export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100165 try {
pineafan63fc5e22022-08-04 22:04:10 +0100166 return (await testMalware(element)).safe;
pineafan813bdf42022-07-24 10:39:10 +0100167 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100168 return true;
pineafan813bdf42022-07-24 10:39:10 +0100169 }
170}
171
pineafan1e462ab2023-03-07 21:34:06 +0000172export function TestString(
173 string: string,
174 soft: string[],
175 strict: string[],
176 enabled?: boolean
177): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000178 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100179 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100180 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100181 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100182 }
183 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100184 for (const word of soft) {
185 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100186 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000187 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100188 }
189 }
190 }
pineafan63fc5e22022-08-04 22:04:10 +0100191 return null;
pineafan813bdf42022-07-24 10:39:10 +0100192}
193
pineafan63fc5e22022-08-04 22:04:10 +0100194export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100195 const text = await Tesseract.recognize(url, {
196 lang: "eng",
197 oem: 1,
198 psm: 3
199 });
pineafan813bdf42022-07-24 10:39:10 +0100200 return text;
201}
pineafan6de4da52023-03-07 20:43:44 +0000202
203export async function doMemberChecks(member: Discord.GuildMember, guild: Discord.Guild): Promise<void> {
204 if (member.user.bot) return;
205 const guildData = await client.database.guilds.read(guild.id);
206 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000207 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
pineafan6de4da52023-03-07 20:43:44 +0000208 // Does the username contain filtered words
209 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
210 // Does the nickname contain filtered words
211 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
212 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000213 const avatarTextCheck = TestString(
214 (await TestImage(member.user.displayAvatarURL({ forceStatic: true }))) ?? "",
215 loose,
216 strict,
217 guildData.filters.wordFilter.enabled
218 );
pineafan6de4da52023-03-07 20:43:44 +0000219 // Is the profile picture NSFW
pineafan1e462ab2023-03-07 21:34:06 +0000220 const avatarCheck =
221 guildData.filters.images.NSFW && (await NSFWCheck(member.user.displayAvatarURL({ forceStatic: true })));
pineafan6de4da52023-03-07 20:43:44 +0000222 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000223 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
pineafan6de4da52023-03-07 20:43:44 +0000224 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000225 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000226 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
pineafan6de4da52023-03-07 20:43:44 +0000227
pineafan1e462ab2023-03-07 21:34:06 +0000228 if (
229 usernameCheck !== null ||
230 nicknameCheck !== null ||
231 avatarCheck ||
232 inviteCheck ||
233 nicknameInviteCheck ||
234 avatarTextCheck !== null
235 ) {
pineafan6de4da52023-03-07 20:43:44 +0000236 const infractions = [];
237 if (usernameCheck !== null) {
238 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000239 }
240 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000241 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000242 }
243 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000244 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000245 }
246 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000247 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000248 }
249 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000250 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000251 }
252 if (avatarTextCheck !== null) {
253 infractions.push(
254 `Profile picture contains a ${avatarTextCheck.type}ly filtered word: ${avatarTextCheck.word}`
255 );
pineafan6de4da52023-03-07 20:43:44 +0000256 }
257 if (infractions.length === 0) return;
258 // This is bad - Warn in the staff notifications channel
259 const filter = getEmojiByName("ICONS.FILTER");
260 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
261 const embed = new EmojiEmbed()
262 .setTitle("Member Flagged")
263 .setEmoji("ICONS.FLAGS.RED")
264 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000265 .setDescription(
266 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
267 infractions.map((element) => `${filter} ${element}`).join("\n")
268 );
pineafan6de4da52023-03-07 20:43:44 +0000269 await channel.send({
270 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000271 components: [
272 new ActionRowBuilder<ButtonBuilder>().addComponents(
273 ...[
274 new ButtonBuilder()
275 .setCustomId(`mod:warn:${member.user.id}`)
276 .setLabel("Warn")
277 .setStyle(ButtonStyle.Primary),
278 new ButtonBuilder()
279 .setCustomId(`mod:mute:${member.user.id}`)
280 .setLabel("Mute")
281 .setStyle(ButtonStyle.Primary),
282 new ButtonBuilder()
283 .setCustomId(`mod:kick:${member.user.id}`)
284 .setLabel("Kick")
285 .setStyle(ButtonStyle.Danger),
286 new ButtonBuilder()
287 .setCustomId(`mod:ban:${member.user.id}`)
288 .setLabel("Ban")
289 .setStyle(ButtonStyle.Danger)
290 ].concat(
291 usernameCheck !== null || nicknameCheck !== null || avatarTextCheck !== null
292 ? [
293 new ButtonBuilder()
294 .setCustomId(`mod:nickname:${member.user.id}`)
295 .setLabel("Change Name")
296 .setStyle(ButtonStyle.Primary)
297 ]
298 : []
299 )
300 )
301 ]
pineafan6de4da52023-03-07 20:43:44 +0000302 });
303 }
pineafan1e462ab2023-03-07 21:34:06 +0000304}