Implement logging for verification failures and enhance moderation responses
- Introduced a new logging event type `VERIFICATION_FAIL` to capture details of failed verification attempts, including reasons and actions taken. - Updated moderation commands to include reasons in success messages for actions like ban, kick, and timeout. - Enhanced the logging of ban and kick actions to include moderator information and reasons fetched from the audit log. - Improved localization for new logging messages in both English and German. - Documented changes in the phase tracking documentation to reflect the new logging capabilities and verification failure handling.
This commit is contained in:
@@ -10,6 +10,9 @@ import type { LogEventType } from '@nexumi/shared';
|
||||
import { ensureGuild } from '../../guild.js';
|
||||
import { logger } from '../../logger.js';
|
||||
|
||||
/** Audit-log entries can lag a moment behind the gateway event. */
|
||||
const AUDIT_LOG_MAX_AGE_MS = 15_000;
|
||||
|
||||
export async function getLoggingConfig(prisma: BotContext['prisma'], guildId: string) {
|
||||
await ensureGuild(prisma, guildId);
|
||||
let config = await prisma.loggingConfig.findUnique({ where: { guildId } });
|
||||
@@ -19,6 +22,36 @@ export async function getLoggingConfig(prisma: BotContext['prisma'], guildId: st
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discord does not send ban/kick reasons over the gateway.
|
||||
* Reasons must be read from the audit log (requires View Audit Log).
|
||||
*/
|
||||
async function fetchRecentAuditEntry(
|
||||
guild: Guild,
|
||||
type: AuditLogEvent,
|
||||
targetId: string
|
||||
): Promise<{ reason: string | null; executorId: string | null } | null> {
|
||||
try {
|
||||
const auditLogs = await guild.fetchAuditLogs({ type, limit: 5 });
|
||||
const entry = auditLogs.entries.find((item) => {
|
||||
if (item.targetId !== targetId) {
|
||||
return false;
|
||||
}
|
||||
return Date.now() - item.createdTimestamp <= AUDIT_LOG_MAX_AGE_MS;
|
||||
});
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
reason: entry.reason ?? null,
|
||||
executorId: entry.executorId ?? entry.executor?.id ?? null
|
||||
};
|
||||
} catch (error) {
|
||||
logger.warn({ error, guildId: guild.id, type }, 'Failed to fetch audit log for logging');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getLogChannelId(
|
||||
prisma: BotContext['prisma'],
|
||||
guildId: string,
|
||||
@@ -124,6 +157,45 @@ export async function logModAction(
|
||||
await sendLogEmbed(context, guild, 'MOD_ACTION', 'Moderation Action', description, 0xef4444);
|
||||
}
|
||||
|
||||
export async function logVerificationFail(
|
||||
context: BotContext,
|
||||
input: {
|
||||
guildId: string;
|
||||
userId: string;
|
||||
userTag?: string;
|
||||
reason: string;
|
||||
detail?: string;
|
||||
failAction?: string;
|
||||
matchedUserId?: string | null;
|
||||
}
|
||||
): Promise<void> {
|
||||
const guild = await context.client.guilds.fetch(input.guildId).catch(() => null);
|
||||
if (!guild) {
|
||||
return;
|
||||
}
|
||||
const lines = [
|
||||
`**User:** ${input.userTag ? `${input.userTag} ` : ''}(<@${input.userId}>) (\`${input.userId}\`)`,
|
||||
`**Reason:** ${input.reason}`
|
||||
];
|
||||
if (input.detail) {
|
||||
lines.push(`**Detail:** ${input.detail}`);
|
||||
}
|
||||
if (input.matchedUserId) {
|
||||
lines.push(`**Matched user:** <@${input.matchedUserId}> (\`${input.matchedUserId}\`)`);
|
||||
}
|
||||
if (input.failAction) {
|
||||
lines.push(`**Fail action:** ${input.failAction}`);
|
||||
}
|
||||
await sendLogEmbed(
|
||||
context,
|
||||
guild,
|
||||
'VERIFICATION_FAIL',
|
||||
'Verification Failed',
|
||||
lines.join('\n'),
|
||||
0xf97316
|
||||
);
|
||||
}
|
||||
|
||||
export async function handleChannelDeleteForAntiNuke(
|
||||
context: BotContext,
|
||||
guild: Guild,
|
||||
@@ -253,6 +325,29 @@ export async function registerLoggingEvents(context: BotContext): Promise<void>
|
||||
if (memberIgnored(config, member as GuildMember, member.user.bot)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const kickEntry = await fetchRecentAuditEntry(
|
||||
member.guild,
|
||||
AuditLogEvent.MemberKick,
|
||||
member.id
|
||||
);
|
||||
|
||||
if (kickEntry) {
|
||||
await sendLogEmbed(
|
||||
context,
|
||||
member.guild,
|
||||
'MEMBER_LEAVE',
|
||||
'Member Kicked',
|
||||
[
|
||||
`**User:** ${member.user.tag} (<@${member.id}>)`,
|
||||
`**Moderator:** ${kickEntry.executorId ? `<@${kickEntry.executorId}>` : '—'}`,
|
||||
`**Reason:** ${kickEntry.reason ?? '—'}`
|
||||
].join('\n'),
|
||||
0xf59e0b
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await sendLogEmbed(
|
||||
context,
|
||||
member.guild,
|
||||
@@ -265,12 +360,19 @@ export async function registerLoggingEvents(context: BotContext): Promise<void>
|
||||
client.on('guildBanAdd', async (ban) => {
|
||||
const guild = ban.guild;
|
||||
await handleBanForAntiNuke(context, guild);
|
||||
|
||||
const audit = await fetchRecentAuditEntry(guild, AuditLogEvent.MemberBanAdd, ban.user.id);
|
||||
const reason = audit?.reason ?? ban.reason ?? '—';
|
||||
const executorLine = audit?.executorId
|
||||
? `\n**Moderator:** <@${audit.executorId}>`
|
||||
: '';
|
||||
|
||||
await sendLogEmbed(
|
||||
context,
|
||||
guild,
|
||||
'MEMBER_BAN',
|
||||
'Member Banned',
|
||||
`**User:** ${ban.user.tag} (<@${ban.user.id}>)\n**Reason:** ${ban.reason ?? '—'}`
|
||||
`**User:** ${ban.user.tag} (<@${ban.user.id}>)${executorLine}\n**Reason:** ${reason}`
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -76,7 +76,10 @@ export async function executeBan(
|
||||
}
|
||||
|
||||
await interaction.editReply({
|
||||
content: tf(locale, 'moderation.success.case', { caseNumber: modCase.caseNumber }),
|
||||
content: tf(locale, 'moderation.success.caseWithReason', {
|
||||
caseNumber: modCase.caseNumber,
|
||||
reason: payload.reason
|
||||
}),
|
||||
components: []
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,9 +54,12 @@ async function ensureMod(
|
||||
async function replySuccessCase(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
locale: 'de' | 'en',
|
||||
caseNumber: number
|
||||
caseNumber: number,
|
||||
reason?: string
|
||||
): Promise<void> {
|
||||
const content = tf(locale, 'moderation.success.case', { caseNumber });
|
||||
const content = reason
|
||||
? tf(locale, 'moderation.success.caseWithReason', { caseNumber, reason })
|
||||
: tf(locale, 'moderation.success.case', { caseNumber });
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.editReply({ content });
|
||||
return;
|
||||
@@ -117,7 +120,7 @@ const unbanCommand: SlashCommand = {
|
||||
action: 'UNBAN',
|
||||
reason
|
||||
});
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber);
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber, reason);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -139,7 +142,7 @@ const kickCommand: SlashCommand = {
|
||||
action: 'KICK',
|
||||
reason
|
||||
});
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber);
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber, reason);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -172,7 +175,7 @@ const timeoutCommand: SlashCommand = {
|
||||
reason,
|
||||
metadata: { durationMs: duration }
|
||||
});
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber);
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber, reason);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -194,7 +197,7 @@ const untimeoutCommand: SlashCommand = {
|
||||
action: 'UN_TIMEOUT',
|
||||
reason
|
||||
});
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber);
|
||||
await replySuccessCase(interaction, locale, modCase.caseNumber, reason);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -71,6 +71,28 @@ async function applyFailAction(
|
||||
}
|
||||
}
|
||||
|
||||
async function logVerificationFailure(
|
||||
context: BotContext,
|
||||
member: GuildMember,
|
||||
input: {
|
||||
reason: string;
|
||||
detail?: string;
|
||||
failAction?: string;
|
||||
matchedUserId?: string | null;
|
||||
}
|
||||
): Promise<void> {
|
||||
const { logVerificationFail } = await import('../logging/events.js');
|
||||
await logVerificationFail(context, {
|
||||
guildId: member.guild.id,
|
||||
userId: member.id,
|
||||
userTag: member.user.tag,
|
||||
reason: input.reason,
|
||||
detail: input.detail,
|
||||
failAction: input.failAction,
|
||||
matchedUserId: input.matchedUserId
|
||||
});
|
||||
}
|
||||
|
||||
export async function completeVerification(
|
||||
context: BotContext,
|
||||
guildId: string,
|
||||
@@ -90,11 +112,13 @@ export async function completeVerification(
|
||||
|
||||
const ageDays = accountAgeDays(member.user.createdAt);
|
||||
if (config.minAccountAgeDays > 0 && ageDays < config.minAccountAgeDays) {
|
||||
await applyFailAction(
|
||||
member,
|
||||
config.failAction,
|
||||
`Verification failed: account too young (${ageDays}d)`
|
||||
);
|
||||
const failReason = `Verification failed: account too young (${ageDays}d)`;
|
||||
await logVerificationFailure(context, member, {
|
||||
reason: 'account_too_young',
|
||||
detail: `Account age ${ageDays}d (required ${config.minAccountAgeDays}d)`,
|
||||
failAction: config.failAction
|
||||
});
|
||||
await applyFailAction(member, config.failAction, failReason);
|
||||
return { ok: false, reason: 'account_too_young' };
|
||||
}
|
||||
|
||||
@@ -170,13 +194,23 @@ export async function completeVerification(
|
||||
});
|
||||
|
||||
if (config.altBlockOnMatch) {
|
||||
await applyFailAction(
|
||||
member,
|
||||
config.failAction,
|
||||
`Verification failed: possible alt account (${match.reason})`
|
||||
);
|
||||
const failReason = `Verification failed: possible alt account (${match.reason})`;
|
||||
await logVerificationFailure(context, member, {
|
||||
reason: 'alt_detected',
|
||||
detail: `Signal: ${match.reason}`,
|
||||
failAction: config.failAction,
|
||||
matchedUserId
|
||||
});
|
||||
await applyFailAction(member, config.failAction, failReason);
|
||||
return { ok: false, reason: 'alt_detected' };
|
||||
}
|
||||
|
||||
await logVerificationFailure(context, member, {
|
||||
reason: 'alt_detected_flagged',
|
||||
detail: `Signal: ${match.reason} (flagged only, not blocked)`,
|
||||
failAction: 'NONE',
|
||||
matchedUserId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user