Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/discord/automod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async function handleAutomodAction(execution: AutoModerationActionExecution) {

// Only log actions that actually affected a message
if (action.type === AutoModerationActionType.Timeout) {
log("debug", "Automod", "Skipping timeout action (no message to log)", {
log("info", "Automod", "Skipping timeout action (no message to log)", {
userId,
guildId: guild.id,
ruleId: autoModerationRule?.name,
Expand Down
1 change: 1 addition & 0 deletions app/discord/client.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const client = new Client({
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.AutoModerationExecution,
Expand Down
2 changes: 2 additions & 0 deletions app/discord/gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import automod from "#~/discord/automod";
import { client, login } from "#~/discord/client.server";
import { deployCommands } from "#~/discord/deployCommands.server";
import { startEscalationResolver } from "#~/discord/escalationResolver";
import modActionLogger from "#~/discord/modActionLogger";
import onboardGuild from "#~/discord/onboardGuild";
import { startReactjiChanneler } from "#~/discord/reactjiChanneler";
import { botStats, shutdownMetrics } from "#~/helpers/metrics";
Expand Down Expand Up @@ -59,6 +60,7 @@ export default function init() {
await Promise.all([
onboardGuild(client),
automod(client),
modActionLogger(client),
deployCommands(client),
startActivityTracking(client),
startHoneypotTracking(client),
Expand Down
214 changes: 214 additions & 0 deletions app/discord/modActionLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import {
AuditLogEvent,
Events,
type Client,
type Guild,
type GuildBan,
type GuildMember,
type PartialGuildMember,
type PartialUser,
type User,
} from "discord.js";

import { reportModAction, type ModActionReport } from "#~/helpers/modLog";
import { log } from "#~/helpers/observability";

// Time window to check audit log for matching entries (5 seconds)
const AUDIT_LOG_WINDOW_MS = 5000;

async function handleBanAdd(ban: GuildBan) {
const { guild, user } = ban;
let { reason } = ban;
let executor: User | PartialUser | null = null;

log("info", "ModActionLogger", "Ban detected", {
userId: user.id,
guildId: guild.id,
reason,
});

try {
// Check audit log for who performed the ban
const auditLogs = await guild.fetchAuditLogs({
type: AuditLogEvent.MemberBanAdd,
limit: 5,
});

const banEntry = auditLogs.entries.find(
(entry) =>
entry.target?.id === user.id &&
Date.now() - entry.createdTimestamp < AUDIT_LOG_WINDOW_MS,
);

executor = banEntry?.executor ?? null;
reason = banEntry?.reason ?? reason;

// Skip if the bot performed this action (it's already logged elsewhere)
if (executor?.id === guild.client.user?.id) {
log("debug", "ModActionLogger", "Skipping self-ban", {
userId: user.id,
guildId: guild.id,
});
return;
}
} catch (error) {
// If we can't access audit log, still log the ban but without executor info
if (
error instanceof Error &&
error.message.includes("Missing Permissions")
) {
log(
"warn",
"ModActionLogger",
"Cannot access audit log for ban details",
{ userId: user.id, guildId: guild.id },
);
} else {
log("error", "ModActionLogger", "Failed to fetch audit log for ban", {
userId: user.id,
guildId: guild.id,
error,
});
}
}

try {
await reportModAction({
guild,
user,
actionType: "ban",
executor,
reason: reason ?? "",
});
} catch (error) {
log("error", "ModActionLogger", "Failed to report ban", {
userId: user.id,
guildId: guild.id,
error,
});
}
}

async function fetchAuditLogs(
guild: Guild,
user: User,
): Promise<ModActionReport | undefined> {
// Check audit log to distinguish kick from voluntary leave
const auditLogs = await guild.fetchAuditLogs({
type: AuditLogEvent.MemberKick,
limit: 5,
});

const kickEntry = auditLogs.entries.find(
(entry) =>
entry.target?.id === user.id &&
Date.now() - entry.createdTimestamp < AUDIT_LOG_WINDOW_MS,
);

// If no kick entry found, user left voluntarily
if (!kickEntry) {
log(
"debug",
"ModActionLogger",
"No kick entry found, user left voluntarily",
{ userId: user.id, guildId: guild.id },
);
return {
actionType: "left",
user,
guild,
executor: undefined,
reason: undefined,
};
}
const { executor, reason } = kickEntry;

if (!executor) {
log(
"warn",
"ModActionLogger",
`No executor found for audit log entry ${kickEntry.id}`,
);
}

// Skip if the bot performed this action
// TODO: maybe best to invert — remove manual kick logs in favor of this
if (kickEntry.executor?.id === guild.client.user?.id) {
log("debug", "ModActionLogger", "Skipping self-kick", {
userId: user.id,
guildId: guild.id,
});
return;
}

return { actionType: "kick", user, guild, executor, reason: reason ?? "" };
}

async function handleMemberRemove(member: GuildMember | PartialGuildMember) {
const { guild, user } = member;

log("info", "ModActionLogger", "Member removal detected", {
userId: user.id,
guildId: guild.id,
});

try {
const auditLogs = await fetchAuditLogs(guild, user);

if (auditLogs) {
const { executor = null, reason = "" } = auditLogs;
await reportModAction({
guild,
user,
actionType: "kick",
executor,
reason,
});
return;
}
await reportModAction({
guild,
user,
actionType: "left",
executor: undefined,
reason: undefined,
});
} catch (error) {
log("error", "ModActionLogger", "Failed to handle member removal", {
userId: user.id,
guildId: guild.id,
error,
});
}
}

export default async (bot: Client) => {
bot.on(Events.GuildBanAdd, async (ban) => {
try {
await handleBanAdd(ban);
} catch (error) {
log("error", "ModActionLogger", "Unhandled error in ban handler", {
userId: ban.user.id,
guildId: ban.guild.id,
error,
});
}
});

bot.on(Events.GuildMemberRemove, async (member) => {
try {
await handleMemberRemove(member);
} catch (error) {
log(
"error",
"ModActionLogger",
"Unhandled error in member remove handler",
{
userId: member.user?.id,
guildId: member.guild.id,
error,
},
);
}
});
};
27 changes: 11 additions & 16 deletions app/helpers/discord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,17 @@ export const describeAttachments = (
return attachments.size === 0
? undefined
: {
description:
"Attachments:\n" +
attachments
.map(
({ size, name, contentType, url }) =>
// Include size of the file and the filename
`${prettyBytes(size)}: ${
// If it's a video or image, include a link.
// Renders as `1.12mb: [some-image.jpg](<original image url>)`
contentType?.match(/(image|video)/)
? `[${name}](${url})`
: name
}`,
)
.join("\n"),
description: attachments
.map(
({ size, name, contentType, url }) =>
// Include size of the file and the filename
`${prettyBytes(size)}: ${
// If it's a video or image, include a link.
// Renders as `1.12mb: [some-image.jpg](<original image url>)`
contentType?.match(/(image|video)/) ? `[${name}](${url})` : name
}`,
)
.join("\n"),
};
};

Expand All @@ -115,7 +111,6 @@ export const describeReactions = (
return reactions.size === 0
? undefined
: {
title: "Reactions",
fields: reactions.map((r) => ({
name: "",
value: `${r.count} ${
Expand Down
Loading