blob: 53c8c9ba585886bb2823f5443f67e5ef78a14d78 [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";
9// import * as clamscan from "clamscan";
10import * as tf from "@tensorflow/tfjs";
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 Grey32179982023-03-07 23:59:06 +000031 const image = tf.tensor3d(new Uint8Array(fileStream));
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 Grey32179982023-03-07 23:59:06 +000040 const [_, hash] = await saveAttachment(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 };
Skyler Grey32179982023-03-07 23:59:06 +000044 // const data = new URLSearchParams();
45 // // const f = createReadStream(p);
46 // data.append("file", f.read(fs.statSync(p).size));
47 // 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 // })
55 // .then((response) =>
56 // response.status === 200 ? (response.json() as Promise<MalwareSchema>) : { safe: true, errored: true }
57 // )
58 // .catch((err) => {
59 // console.error(err);
60 // return { safe: true, errored: true };
61 // });
62 // if (!result.errored) {
63 // client.database.scanCache.write(hash, "malware", result.safe);
64 // }
65 // return { safe: result.safe };
pineafan3a02ea32022-08-11 21:35:04 +010066}
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 Grey32179982023-03-07 23:59:06 +000093 const enc = new TextDecoder("utf-8");
94 return [image, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
95}
96
97export async function saveAttachment(link: string): Promise<[string, string]> {
98 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey75ea9172022-08-06 10:22:23 +010099 const fileName = generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -0500100 const enc = new TextDecoder("utf-8");
101 writeFileSync(fileName, new DataView(image), "base64");
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
pineafan63fc5e22022-08-04 22:04:10 +0100156export async function NSFWCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100157 try {
TheCodedProfb5e9d552023-01-29 15:43:26 -0500158 return (await testNSFW(element)).nsfw;
pineafan813bdf42022-07-24 10:39:10 +0100159 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100160 return false;
pineafan813bdf42022-07-24 10:39:10 +0100161 }
162}
163
Skyler Grey11236ba2022-08-08 21:13:33 +0100164export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100165 if (element.height === null || element.width === null) return true;
166 if (element.height < 20 || element.width < 20) return false;
167 return true;
pineafan813bdf42022-07-24 10:39:10 +0100168}
169
pineafan63fc5e22022-08-04 22:04:10 +0100170export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100171 try {
pineafan63fc5e22022-08-04 22:04:10 +0100172 return (await testMalware(element)).safe;
pineafan813bdf42022-07-24 10:39:10 +0100173 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100174 return true;
pineafan813bdf42022-07-24 10:39:10 +0100175 }
176}
177
pineafan1e462ab2023-03-07 21:34:06 +0000178export function TestString(
179 string: string,
180 soft: string[],
181 strict: string[],
182 enabled?: boolean
183): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000184 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100185 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100186 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100187 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100188 }
189 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100190 for (const word of soft) {
191 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100192 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000193 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100194 }
195 }
196 }
pineafan63fc5e22022-08-04 22:04:10 +0100197 return null;
pineafan813bdf42022-07-24 10:39:10 +0100198}
199
pineafan63fc5e22022-08-04 22:04:10 +0100200export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100201 const text = await Tesseract.recognize(url, {
202 lang: "eng",
203 oem: 1,
204 psm: 3
205 });
pineafan813bdf42022-07-24 10:39:10 +0100206 return text;
207}
pineafan6de4da52023-03-07 20:43:44 +0000208
209export async function doMemberChecks(member: Discord.GuildMember, guild: Discord.Guild): Promise<void> {
210 if (member.user.bot) return;
211 const guildData = await client.database.guilds.read(guild.id);
212 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000213 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
pineafan6de4da52023-03-07 20:43:44 +0000214 // Does the username contain filtered words
215 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
216 // Does the nickname contain filtered words
217 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
218 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000219 const avatarTextCheck = TestString(
220 (await TestImage(member.user.displayAvatarURL({ forceStatic: true }))) ?? "",
221 loose,
222 strict,
223 guildData.filters.wordFilter.enabled
224 );
pineafan6de4da52023-03-07 20:43:44 +0000225 // Is the profile picture NSFW
pineafan1e462ab2023-03-07 21:34:06 +0000226 const avatarCheck =
227 guildData.filters.images.NSFW && (await NSFWCheck(member.user.displayAvatarURL({ forceStatic: true })));
pineafan6de4da52023-03-07 20:43:44 +0000228 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000229 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
pineafan6de4da52023-03-07 20:43:44 +0000230 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000231 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000232 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
pineafan6de4da52023-03-07 20:43:44 +0000233
pineafan1e462ab2023-03-07 21:34:06 +0000234 if (
235 usernameCheck !== null ||
236 nicknameCheck !== null ||
237 avatarCheck ||
238 inviteCheck ||
239 nicknameInviteCheck ||
240 avatarTextCheck !== null
241 ) {
pineafan6de4da52023-03-07 20:43:44 +0000242 const infractions = [];
243 if (usernameCheck !== null) {
244 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000245 }
246 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000247 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000248 }
249 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000250 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000251 }
252 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000253 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000254 }
255 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000256 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000257 }
258 if (avatarTextCheck !== null) {
259 infractions.push(
260 `Profile picture contains a ${avatarTextCheck.type}ly filtered word: ${avatarTextCheck.word}`
261 );
pineafan6de4da52023-03-07 20:43:44 +0000262 }
263 if (infractions.length === 0) return;
264 // This is bad - Warn in the staff notifications channel
265 const filter = getEmojiByName("ICONS.FILTER");
266 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
267 const embed = new EmojiEmbed()
268 .setTitle("Member Flagged")
269 .setEmoji("ICONS.FLAGS.RED")
270 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000271 .setDescription(
272 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
273 infractions.map((element) => `${filter} ${element}`).join("\n")
274 );
pineafan6de4da52023-03-07 20:43:44 +0000275 await channel.send({
276 embeds: [embed],
pineafan1e462ab2023-03-07 21:34:06 +0000277 components: [
278 new ActionRowBuilder<ButtonBuilder>().addComponents(
279 ...[
280 new ButtonBuilder()
281 .setCustomId(`mod:warn:${member.user.id}`)
282 .setLabel("Warn")
283 .setStyle(ButtonStyle.Primary),
284 new ButtonBuilder()
285 .setCustomId(`mod:mute:${member.user.id}`)
286 .setLabel("Mute")
287 .setStyle(ButtonStyle.Primary),
288 new ButtonBuilder()
289 .setCustomId(`mod:kick:${member.user.id}`)
290 .setLabel("Kick")
291 .setStyle(ButtonStyle.Danger),
292 new ButtonBuilder()
293 .setCustomId(`mod:ban:${member.user.id}`)
294 .setLabel("Ban")
295 .setStyle(ButtonStyle.Danger)
296 ].concat(
297 usernameCheck !== null || nicknameCheck !== null || avatarTextCheck !== null
298 ? [
299 new ButtonBuilder()
300 .setCustomId(`mod:nickname:${member.user.id}`)
301 .setLabel("Change Name")
302 .setStyle(ButtonStyle.Primary)
303 ]
304 : []
305 )
306 )
307 ]
pineafan6de4da52023-03-07 20:43:44 +0000308 });
309 }
pineafan1e462ab2023-03-07 21:34:06 +0000310}