Implement premium features and GDPR compliance in bot and WebUI

- Added new models for premium tier configurations and assignments, enabling feature limits for free and premium users.
- Introduced GDPR deletion logging and commands for user data management.
- Enhanced logging configuration with retention days for audit logs.
- Updated bot commands and job processing to include new premium and GDPR functionalities.
- Improved localization with new keys for premium features and GDPR commands in both English and German.
- Added UI components for managing premium settings and logging retention in the WebUI.
This commit is contained in:
smueller
2026-07-22 16:59:23 +02:00
parent 4852f16f79
commit 08af99ed52
42 changed files with 1546 additions and 30 deletions

View File

@@ -1,6 +1,6 @@
/** Module id → top-level slash command names for `/help`. */
export const HELP_MODULES: ReadonlyArray<{ id: string; commands: readonly string[] }> = [
{ id: 'core', commands: ['help', 'info', 'invite', 'support'] },
{ id: 'core', commands: ['help', 'info', 'invite', 'support', 'privacy', 'gdpr'] },
{
id: 'moderation',
commands: [

View File

@@ -4,6 +4,7 @@ import { applyFeedTemplate, SocialFeedTypeSchema } from '@nexumi/shared';
import { z } from 'zod';
import { ensureGuild } from '../../guild.js';
import { logger } from '../../logger.js';
import { assertPremiumLimit, PremiumLimitError } from '../../premium.js';
import type { BotContext } from '../../types.js';
import { fetchFeedItems, type FeedItem, type FetchResult } from './fetchers.js';
@@ -49,6 +50,16 @@ export async function addFeed(
await ensureGuild(prisma, guildId);
const sourceId = normalizeFeedSource(input.type, input.source);
const currentCount = await prisma.socialFeed.count({ where: { guildId } });
try {
await assertPremiumLimit(prisma, guildId, 'feeds', currentCount);
} catch (error) {
if (error instanceof PremiumLimitError) {
throw new FeedError(error.code === 'feature_disabled' ? 'premium_feature' : 'premium_limit');
}
throw error;
}
return prisma.socialFeed.create({
data: {
guildId,

View File

@@ -0,0 +1,22 @@
import {
applyCommandDescription,
applyOptionDescription
} from '@nexumi/shared';
import { SlashCommandBuilder } from 'discord.js';
export const privacyCommandData = applyCommandDescription(
new SlashCommandBuilder().setName('privacy'),
'gdpr.privacy.description'
);
export const gdprCommandData = applyCommandDescription(
new SlashCommandBuilder().setName('gdpr'),
'gdpr.command.description'
).addSubcommand((sub) =>
applyCommandDescription(sub.setName('delete'), 'gdpr.delete.description').addBooleanOption((option) =>
applyOptionDescription(
option.setName('confirm').setRequired(true),
'gdpr.delete.options.confirm'
)
)
);

View File

@@ -0,0 +1,77 @@
import { EmbedBuilder } from 'discord.js';
import { t, tf } from '@nexumi/shared';
import type { SlashCommand } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { env } from '../../env.js';
import { privacyCommandData, gdprCommandData } from './command-definitions.js';
import { deleteUserPersonalData } from './service.js';
const NEXUMI_COLOR = 0x6366f1;
function privacyUrl(): string {
const base = (env.WEBUI_URL ?? env.PUBLIC_BASE_URL).replace(/\/$/, '');
return `${base}/privacy`;
}
const privacyCommand: SlashCommand = {
data: privacyCommandData,
async execute(interaction, context) {
const locale = await getGuildLocale(context.prisma, interaction.guildId);
const embed = new EmbedBuilder()
.setTitle(t(locale, 'gdpr.privacy.title'))
.setColor(NEXUMI_COLOR)
.setDescription(
[
t(locale, 'gdpr.privacy.body'),
'',
tf(locale, 'gdpr.privacy.link', { url: privacyUrl() }),
t(locale, 'gdpr.privacy.deleteHint')
].join('\n')
);
await interaction.reply({ embeds: [embed], ephemeral: true });
}
};
const gdprCommand: SlashCommand = {
data: gdprCommandData,
async execute(interaction, context) {
const locale = await getGuildLocale(context.prisma, interaction.guildId);
const sub = interaction.options.getSubcommand(true);
if (sub !== 'delete') {
await interaction.reply({ content: t(locale, 'generic.unknownCommand'), ephemeral: true });
return;
}
const confirmed = interaction.options.getBoolean('confirm', true);
if (!confirmed) {
await interaction.reply({
content: t(locale, 'gdpr.delete.needConfirm'),
ephemeral: true
});
return;
}
await interaction.deferReply({ ephemeral: true });
const summary = await deleteUserPersonalData(
context.prisma,
interaction.user.id,
interaction.guildId
);
const embed = new EmbedBuilder()
.setTitle(t(locale, 'gdpr.delete.doneTitle'))
.setColor(NEXUMI_COLOR)
.setDescription(
tf(locale, 'gdpr.delete.doneBody', {
warnings: summary.warnings,
levels: summary.memberLevels,
economy: summary.memberEconomies,
cases: summary.casesAnonymized
})
);
await interaction.editReply({ embeds: [embed] });
}
};
export const gdprCommands: SlashCommand[] = [privacyCommand, gdprCommand];

View File

@@ -0,0 +1,2 @@
export { gdprCommands } from './commands.js';
export { deleteUserPersonalData } from './service.js';

View File

@@ -0,0 +1,96 @@
import type { PrismaClient } from '@prisma/client';
export type GdprDeletionSummary = {
warnings: number;
modNotes: number;
memberLevels: number;
memberEconomies: number;
inventoryItems: number;
birthdays: number;
afkStatuses: number;
reminders: number;
inviteStats: number;
casesAnonymized: number;
userPremium: number;
userRecord: number;
};
/**
* Deletes or anonymizes personal data for a Discord user across guilds.
* Moderation case history is anonymized (targetUserId cleared to a placeholder)
* so server audit integrity is preserved.
*/
export async function deleteUserPersonalData(
prisma: PrismaClient,
userId: string,
guildId: string | null
): Promise<GdprDeletionSummary> {
const scope = guildId ? { guildId, userId } : { userId };
const caseScope = guildId
? { guildId, targetUserId: userId }
: { targetUserId: userId };
const [
warnings,
modNotes,
memberLevels,
memberEconomies,
inventoryItems,
birthdays,
afkStatuses,
reminders,
inviteStats,
inviteJoins,
casesAnonymized,
userPremium
] = await prisma.$transaction([
prisma.warning.deleteMany({ where: scope }),
prisma.modNote.deleteMany({ where: scope }),
prisma.memberLevel.deleteMany({ where: scope }),
prisma.memberEconomy.deleteMany({ where: scope }),
prisma.inventoryItem.deleteMany({ where: scope }),
prisma.birthday.deleteMany({ where: scope }),
prisma.afkStatus.deleteMany({ where: scope }),
prisma.reminder.deleteMany({ where: { userId, ...(guildId ? { guildId } : {}) } }),
prisma.inviteStat.deleteMany({
where: guildId ? { guildId, inviterId: userId } : { inviterId: userId }
}),
prisma.inviteJoin.deleteMany({ where: scope }),
prisma.case.updateMany({
where: caseScope,
data: { targetUserId: '0', reason: '[redacted GDPR deletion]' }
}),
prisma.userPremiumAssignment.deleteMany({ where: { userId } })
]);
let userRecord = 0;
if (!guildId) {
const deleted = await prisma.user.deleteMany({ where: { id: userId } });
userRecord = deleted.count;
}
const summary: GdprDeletionSummary = {
warnings: warnings.count,
modNotes: modNotes.count,
memberLevels: memberLevels.count,
memberEconomies: memberEconomies.count,
inventoryItems: inventoryItems.count,
birthdays: birthdays.count,
afkStatuses: afkStatuses.count,
reminders: reminders.count,
inviteStats: inviteStats.count + inviteJoins.count,
casesAnonymized: casesAnonymized.count,
userPremium: userPremium.count,
userRecord
};
await prisma.gdprDeletionLog.create({
data: {
userId,
guildId,
summary
}
});
return summary;
}

View File

@@ -11,6 +11,7 @@ import { GuildBackupPayloadSchema, type GuildBackupPayload } from '@nexumi/share
import type { GuildBackup } from '@prisma/client';
import { ensureGuild } from '../../guild.js';
import { logger } from '../../logger.js';
import { assertPremiumLimit, PremiumLimitError } from '../../premium.js';
import { guildBackupQueue } from '../../queues.js';
import type { BotContext } from '../../types.js';
@@ -46,6 +47,18 @@ export async function createGuildBackup(
await ensureGuild(context.prisma, guild.id);
const currentCount = await context.prisma.guildBackup.count({ where: { guildId: guild.id } });
try {
await assertPremiumLimit(context.prisma, guild.id, 'backups', currentCount);
} catch (error) {
if (error instanceof PremiumLimitError) {
throw new GuildBackupError(
error.code === 'feature_disabled' ? 'premium_feature' : 'premium_limit'
);
}
throw error;
}
return context.prisma.guildBackup.create({
data: {
guildId: guild.id,

View File

@@ -8,6 +8,7 @@ import {
import type { Tag } from '@prisma/client';
import { ensureGuild } from '../../guild.js';
import type { BotContext } from '../../types.js';
import { assertPremiumLimit, PremiumLimitError } from '../../premium.js';
export class TagError extends Error {
constructor(public readonly code: string) {
@@ -153,6 +154,16 @@ export async function createTag(
throw new TagError('embed_required');
}
const currentCount = await context.prisma.tag.count({ where: { guildId: params.guildId } });
try {
await assertPremiumLimit(context.prisma, params.guildId, 'tags', currentCount);
} catch (error) {
if (error instanceof PremiumLimitError) {
throw new TagError(error.code === 'feature_disabled' ? 'premium_feature' : 'premium_limit');
}
throw error;
}
return context.prisma.tag.create({
data: {
guildId: params.guildId,

View File

@@ -30,7 +30,7 @@ import {
import { createPoll } from './poll.js';
import { createReminder, deleteReminder, listReminders } from './reminders.js';
import { setAfk } from './afk.js';
import { getDeletedSnipe, getEditedSnipe } from './snipe.js';
import { getDeletedSnipe, getEditedSnipe, isSnipeEnabled } from './snipe.js';
import {
UtilityError,
buildChannelInfoEmbed,
@@ -373,6 +373,10 @@ const snipeCommand: SlashCommand = {
async execute(interaction, context) {
const locale = await getGuildLocale(context.prisma, interaction.guildId);
if (!(await ensureGuildCommand(interaction, locale))) return;
if (!(await isSnipeEnabled(context, interaction.guildId!))) {
await interaction.reply({ content: t(locale, 'utility.snipe.disabled'), ephemeral: true });
return;
}
const result = await getDeletedSnipe(context, interaction.channelId!, locale);
if (!result) {
@@ -392,6 +396,10 @@ const editsnipeCommand: SlashCommand = {
async execute(interaction, context) {
const locale = await getGuildLocale(context.prisma, interaction.guildId);
if (!(await ensureGuildCommand(interaction, locale))) return;
if (!(await isSnipeEnabled(context, interaction.guildId!))) {
await interaction.reply({ content: t(locale, 'utility.snipe.disabled'), ephemeral: true });
return;
}
const result = await getEditedSnipe(context, interaction.channelId!, locale);
if (!result) {

View File

@@ -58,6 +58,9 @@ export function registerSnipeEvents(context: BotContext): void {
if (message.author?.bot || !message.guildId || !message.channelId) {
return;
}
if (!(await isSnipeEnabled(context, message.guildId))) {
return;
}
if (!message.content && message.attachments.size === 0) {
return;
}
@@ -68,6 +71,9 @@ export function registerSnipeEvents(context: BotContext): void {
if (oldMessage.author?.bot || !oldMessage.guildId || !oldMessage.channelId) {
return;
}
if (!(await isSnipeEnabled(context, oldMessage.guildId))) {
return;
}
const oldContent = oldMessage.content ?? '';
const newContent = newMessage.content ?? '';
if (!oldContent || oldContent === newContent) {
@@ -77,6 +83,14 @@ export function registerSnipeEvents(context: BotContext): void {
});
}
export async function isSnipeEnabled(context: BotContext, guildId: string): Promise<boolean> {
const settings = await context.prisma.guildSettings.findUnique({
where: { guildId },
select: { snipeEnabled: true }
});
return settings?.snipeEnabled ?? false;
}
export async function getDeletedSnipe(
context: BotContext,
channelId: string,