all repos — stealth-developers @ a78eed8b66665f02ed3de6a3c6749c475061b59e

pkgs/bot/src/automod/index.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
import { rest } from "@/discord";
import {
	ChannelType,
	type Client,
	type Message,
	type RESTGetAPIGuildMessagesSearchQuery,
	type RESTGetAPIGuildMessagesSearchResult,
	type Snowflake,
} from "discord.js";
import { distance } from "fastest-levenshtein";
import Tesseract from "tesseract.js";
import imageHash from "imghash";

import { hasManagerPermissions } from "@/utils/discord/permissions";
import { loggers } from "@/utils/logging";
import { db } from "@/database";
import { automodHashes } from "@/database/schema/automod";
import { isProd } from "@/config";
const logger = loggers.automod;

type Pending = {
	channels: Set<Snowflake>;
	reasons: Set<string>;
	timer: NodeJS.Timeout;
};

const pendingReports = new Map<Snowflake, Pending>();
const cooldowns = new Map<Snowflake, NodeJS.Timeout>();

async function getLogChannel(client: Client) {
	return client.channels.fetch(
		isProd ? "1493015326554587146" : "1493015912234881205",
	);
}

type AutomodResult = { delete: true } | null;
type AutomodSignals = {
	messageCount?: number;
	lastMessage?: Message;
};
type AutomodFunction = (
	client: Client,
	message: Message,
) => Promise<AutomodResult>;

// oxlint-disable-next-line no-unused-vars
async function fetchSignals(
	client: Client,
	message: Message,
): Promise<AutomodSignals> {
	const signals: AutomodSignals = {
		messageCount: undefined,
	};

	const messages = (await rest.get(
		`/guilds/${message.guildId}/messages/search`,
		{
			body: {
				author_id: [message.author.id],
			} as RESTGetAPIGuildMessagesSearchQuery,
		},
	)) as RESTGetAPIGuildMessagesSearchResult;

	if ("total_results" in messages) {
		signals.messageCount = messages.total_results;
		const [lastApiMessage] = messages.messages[1];

		const channel = await client.channels.fetch(lastApiMessage.channel_id);
		if (channel?.isTextBased()) {
			const lastMessage = await channel.messages
				.fetch(lastApiMessage.id)
				.catch(() => null);
			if (lastMessage) {
				signals.lastMessage = lastMessage;
			}
		}
	}

	return signals;
}

function hammingDistance(hex1: string, hex2: string): number {
	let dist = 0;
	const len = Math.min(hex1.length, hex2.length);
	for (let i = 0; i < len; i++) {
		const val1 = Number.parseInt(hex1[i], 16);
		const val2 = Number.parseInt(hex2[i], 16);
		let diff = val1 ^ val2;
		while (diff > 0) {
			dist += diff & 1;
			diff >>= 1;
		}
	}
	return dist;
}

export async function handleMessage(client: Client, message: Message) {
	if (message.author.bot || !message.guildId || !message.member) return;
	const automodFunctions: AutomodFunction[] = [
		handleSpamMarker,
		handleCryptoScamOCR,
	];

	if (
		message.channel.type == ChannelType.GuildText &&
		message.channel.name.includes("ticket")
	)
		return;
	if (message.channel.isThread()) return null;
	if (message.content.includes("!bypass")) return null;
	if ((await hasManagerPermissions(message.member)) && isProd) return null;

	for (const func of automodFunctions) {
		const result = await func(client, message);

		if (result?.delete) {
			await message.delete().catch(() => null);
			break;
		}
	}
}

async function reportToAutomod(
	client: Client,
	message: Message,
	reason: string,
	userReply: string,
) {
	if (cooldowns.has(message.author.id)) return;

	const existing = pendingReports.get(message.author.id);
	if (!existing) {
		if (userReply) await message.reply(userReply).catch(() => null);

		const logChannel = await getLogChannel(client);
		if (logChannel?.isSendable()) {
			await message.forward(logChannel).catch(() => null);
			logChannel
				.send(
					`Deleted a message from <@${message.author.id}> in <#${message.channelId}>.\n> ${reason}`,
				)
				.catch(() => null);
		}

		const timer = setTimeout(
			() => flushReport(client, message.author.id),
			30_000,
		);
		pendingReports.set(message.author.id, {
			channels: new Set([message.channelId]),
			reasons: new Set([reason]),
			timer,
		});
	} else {
		existing.channels.add(message.channelId);
		existing.reasons.add(reason);

		clearTimeout(existing.timer);
		existing.timer = setTimeout(
			() => flushReport(client, message.author.id),
			30_000,
		);
	}
}

async function handleCryptoScamOCR(
	client: Client,
	message: Message,
): Promise<AutomodResult> {
	if (message.attachments.size === 0) return null;

	if (
		pendingReports.has(message.author.id) ||
		cooldowns.has(message.author.id)
	) {
		logger.info(
			{ messageId: message.id, authorId: message.author.id },
			"Skipping OCR as user has already been recently flagged",
		);

		await reportToAutomod(
			client,
			message,
			"User repeatedly sending images after being flagged",
			"You sent an image indicative of your account being compromised or a phishing attempt, so we removed it.",
		);

		return { delete: true };
	}

	const scamPatterns = [
		"excited announce launch very own crypto casino",
		"launching my own crypto casino",
		"check out my crypto casino",
		"claim your reward",
		"special promo code",
	];

	for (const attachment of message.attachments.values()) {
		if (!attachment.contentType?.startsWith("image/")) continue;

		try {
			logger.debug(
				{ messageId: message.id, attachmentUrl: attachment.url },
				"Fetching image for hash/OCR",
			);

			const imageResponse = await fetch(attachment.url);
			if (!imageResponse.ok) continue;

			const arrayBuffer = await imageResponse.arrayBuffer();
			const buffer = Buffer.from(arrayBuffer);

			const pHash = await imageHash.hash(buffer);

			const existingHashes = await db.select().from(automodHashes);

			let matchedHash = false;
			for (const existing of existingHashes) {
				const dist = hammingDistance(pHash, existing.hash);
				if (dist <= 12) {
					matchedHash = true;
					break;
				}
			}

			if (matchedHash) {
				logger.info(
					{
						messageId: message.id,
						authorId: message.author.id,
						imageHash: pHash,
					},
					"Image matches known scam hash in DB, skipping OCR",
				);

				await reportToAutomod(
					client,
					message,
					"Image matched known scam hash",
					"You sent an image indicative of your account being compromised or a phishing attempt, so we removed it.",
				);

				return { delete: true };
			}

			logger.debug(
				{ messageId: message.id, imageHash: pHash },
				"Running OCR on image attachment",
			);

			const {
				data: { text },
			} = await Tesseract.recognize(buffer, "eng", {
				errorHandler: (err) => logger.warn({ err }, "OCR error"),
			});

			const normalizedText = text
				.toLowerCase()
				.replace(/[^\w\s]/g, " ")
				.replace(/\s+/g, " ")
				.trim();

			logger.debug(
				{ messageId: message.id, extractedText: normalizedText },
				"OCR completed",
			);

			let isScam = scamPatterns.some((pattern) =>
				normalizedText.includes(pattern),
			);

			if (!isScam) {
				const words = normalizedText.split(" ");

				for (const pattern of scamPatterns) {
					const patternWords = pattern.split(" ");
					const windowSize = patternWords.length;

					for (let i = 0; i <= words.length - windowSize; i++) {
						const window = words.slice(i, i + windowSize).join(" ");
						const similarity =
							1 -
							distance(pattern, window) /
								Math.max(pattern.length, window.length);

						if (similarity > 0.7) {
							logger.info(
								{
									messageId: message.id,
									pattern,
									window,
									similarity,
								},
								"fuzzy match found",
							);
							isScam = true;
							break;
						}
					}

					if (isScam) break;
				}
			}

			const suspiciousKeywords = [
				"crypto",
				"luxgamb",
				"promo code",
				"claim reward",
				"bonus will be deleted",
				"deleted in an hour",
			];

			const hasSuspiciousKeyword = suspiciousKeywords.some((keyword) =>
				normalizedText.includes(keyword),
			);

			if (isScam || hasSuspiciousKeyword) {
				logger.info(
					{
						messageId: message.id,
						authorId: message.author.id,
						isScam,
						hasSuspiciousKeyword,
					},
					"detected probable crypto scam",
				);

				try {
					await db
						.insert(automodHashes)
						.values({
							hash: pHash,
							addedAt: Date.now(),
						})
						.onConflictDoNothing();

					logger.debug(
						{ messageId: message.id, imageHash: pHash },
						"saved scam image hash to DB",
					);
				} catch (err) {
					logger.error(
						{ err, imageHash: pHash },
						"failed to save scam image hash to DB",
					);
				}
			}

			if (isScam) {
				await reportToAutomod(
					client,
					message,
					"OCR detected probable crypto scam",
					"You sent an image indicative of your account being compromised or a phishing attempt, so we removed it.",
				);

				return { delete: true };
			}

			if (hasSuspiciousKeyword) {
				await reportToAutomod(
					client,
					message,
					"OCR detected suspicious keywords",
					"You sent an image that contained suspicious keywords indicative of your account being compromised or a phishing attempt, so we removed it.",
				);

				return { delete: true };
			}
		} catch (err) {
			logger.error(
				{ err, messageId: message.id },
				"failed to process image for ocr",
			);
		}
	}

	return null;
}

async function handleSpamMarker(
	client: Client,
	message: Message,
): Promise<AutomodResult> {
	const { content } = message;

	/*
  	a message will contain either no markers, a link marker or a word maker,
  	likely not two at once.

  	if a messsage contains a link marker, then we delete it.
  	if a message contains a word marker, we first check if the last message
       is older than an hour, if it is, we delete the message.
	*/
	const linkMarkers = [
		"discord.gg/",
		"discordapp.com/invite/",
		"discord.com/invite/",
	];
	const wordMarkers = ["check my bio"];

	const hasLinkMarker = linkMarkers.some((marker) =>
		content.toLowerCase().includes(marker),
	);
	const hasWordMarker = wordMarkers.some((marker) =>
		content.toLowerCase().includes(marker),
	);

	if (!hasLinkMarker && !hasWordMarker) return null;
	// const signals = await fetchSignals(client, message);

	// if (
	// 	hasWordMarker &&
	// 	signals.lastMessage &&
	// 	Date.now() - signals.lastMessage.createdTimestamp < ONE_HOUR
	// ) {
	// 	logger.debug(
	// 		{
	// 			messageId: message.id,
	// 			authorId: message.author.id,
	// 			lastMessageId: signals.lastMessage.id,
	// 			lastMessageAge: Date.now() - signals.lastMessage.createdTimestamp,
	// 		},
	// 		"skipping deletion due to recent message",
	// 	);
	// 	return null;
	// }

	await reportToAutomod(
		client,
		message,
		"potential phishing marker",
		`<@${message.author.id}>, your message contained something indicative of a compromised account or phishing attempt, so we removed it. Keep in mind, we don't allow advertising other servers here.`,
	);

	return { delete: true };
}

async function flushReport(client: Client, authorId: Snowflake) {
	const pending = pendingReports.get(authorId);
	if (!pending) return;

	pendingReports.delete(authorId);
	clearTimeout(pending.timer);

	const logChannel = await getLogChannel(client);
	if (!logChannel?.isSendable()) return;

	const channels = Array.from(pending.channels);
	const channelMentions = channels.map((c) => `<#${c}>`).join(", ");
	const reasons = Array.from(pending.reasons).join(" | ");

	logChannel.send(
		`<@${authorId}> posted flagged messages in channels: ${channelMentions}\n> ${reasons}`,
	);

	const cooldownTimer = setTimeout(
		() => cooldowns.delete(authorId),
		5 * 60 * 1000,
	);
	cooldowns.set(authorId, cooldownTimer);
}