import { ChannelType, REST, Routes } from 'discord.js'; import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js'; import { env } from '../../config/env.js'; import { ExternalApiError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.js'; import { canActOn, getAccessLevel } from '../../core/permissions.js'; import { logEvent } from '../../database/repositories/event-log-repository.js'; import { countByAction, listActions, recordAction, } from '../../database/repositories/moderation-repository.js'; import { listNotificationChannels, removeNotificationChannel, setNotificationChannel, } from '../../database/repositories/notification-repository.js'; import { sendModerationLog } from '../../services/moderation/moderation-service.js'; import { badRequest, forbidden, notFound } from '../http.js'; /** Discord server management from the dashboard (M16-T05). */ const log = createLogger('web:discord'); const guildId = () => env.discord.guildId; function guildOf(context) { const guild = context.client?.guilds?.cache?.get(guildId()); if (!guild) throw badRequest('Le bot n’est connecté à aucun serveur pour l’instant.'); return guild; } /** Resolves the caller as a guild member so the role hierarchy can be enforced. */ async function actingMember(guild, actor) { if (!actor.userId) throw forbidden('Cette action demande une session Discord, pas un jeton d’API.'); const member = await guild.members.fetch(actor.userId).catch(() => null); if (!member) throw forbidden('Ton compte n’est plus membre du serveur.'); return member; } const CHANNEL_KINDS = { [ChannelType.GuildText]: 'text', [ChannelType.GuildVoice]: 'voice', [ChannelType.GuildCategory]: 'category', [ChannelType.GuildAnnouncement]: 'announcement', [ChannelType.GuildStageVoice]: 'stage', [ChannelType.GuildForum]: 'forum', }; const summarizeMember = (member) => ({ id: member.id, username: member.user.username, displayName: member.displayName, avatar: member.displayAvatarURL({ size: 64 }), bot: member.user.bot, joinedAt: member.joinedAt?.toISOString() ?? null, createdAt: member.user.createdAt?.toISOString() ?? null, roles: member.roles.cache.filter((role) => role.id !== member.guild.id).map((role) => role.id), accessLevel: getAccessLevel(member), accessLabel: ACCESS_LABELS[getAccessLevel(member)], timeoutUntil: member.communicationDisabledUntil?.toISOString() ?? null, }); export function registerDiscordRoutes(router) { router.get( '/api/discord/guild', async ({ context }) => { const guild = guildOf(context); await guild.channels.fetch().catch(() => null); return { id: guild.id, name: guild.name, description: guild.description, icon: guild.iconURL({ size: 256 }), banner: guild.bannerURL({ size: 512 }), ownerId: guild.ownerId, memberCount: guild.memberCount, createdAt: guild.createdAt?.toISOString() ?? null, boostTier: guild.premiumTier, boostCount: guild.premiumSubscriptionCount, verificationLevel: guild.verificationLevel, features: guild.features, channels: guild.channels.cache .map((channel) => ({ id: channel.id, name: channel.name, kind: CHANNEL_KINDS[channel.type] ?? 'other', parentId: channel.parentId, position: channel.rawPosition, nsfw: channel.nsfw ?? false, topic: channel.topic ?? null, })) .sort((a, b) => a.position - b.position), roles: guild.roles.cache .filter((role) => role.id !== guild.id) .map((role) => ({ id: role.id, name: role.name, color: role.hexColor, position: role.position, managed: role.managed, mentionable: role.mentionable, memberCount: role.members.size, })) .sort((a, b) => b.position - a.position), mapping: { roles: env.roles, channels: env.channels, }, }; }, { access: ACCESS_LEVELS.STAFF }, ); router.get( '/api/discord/members', async ({ context, query }) => { const guild = guildOf(context); const search = (query.get('q') ?? '').trim().toLowerCase(); const limit = Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200); const members = await guild.members.fetch().catch(() => guild.members.cache); const matched = members .filter((member) => search === '' ? true : member.user.username.toLowerCase().includes(search) || member.displayName.toLowerCase().includes(search) || member.id === search, ) .first(limit); return { total: guild.memberCount, members: matched.map(summarizeMember) }; }, { access: ACCESS_LEVELS.STAFF }, ); router.get( '/api/discord/members/:id', async ({ context, params }) => { const guild = guildOf(context); const member = await guild.members.fetch(params.id).catch(() => null); if (!member) throw notFound('Membre introuvable sur le serveur.'); return { ...summarizeMember(member), history: listActions({ guildId: guild.id, targetId: member.id, limit: 50 }), }; }, { access: ACCESS_LEVELS.STAFF }, ); router.post( '/api/discord/members/:id/roles', async ({ context, params, body, actor }) => { const guild = guildOf(context); const actorMember = await actingMember(guild, actor); const member = await guild.members.fetch(params.id).catch(() => null); if (!member) throw notFound('Membre introuvable sur le serveur.'); if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); const roleId = String(body.roleId ?? ''); const role = guild.roles.cache.get(roleId); if (!role) throw badRequest('Rôle introuvable.'); if (role.position >= actorMember.roles.highest.position && guild.ownerId !== actorMember.id) { throw forbidden('Ce rôle est au-dessus du tien.'); } const action = body.action === 'remove' ? 'remove' : 'add'; if (action === 'add') await member.roles.add(role, `Tableau de bord — ${actor.username}`); else await member.roles.remove(role, `Tableau de bord — ${actor.username}`); recordAction({ guildId: guild.id, action: 'role', moderatorId: actor.userId, targetId: member.id, reason: `${action === 'add' ? 'Ajout' : 'Retrait'} du rôle ${role.name} depuis le tableau de bord`, }); return { ok: true, roles: summarizeMember(member).roles }; }, { access: ACCESS_LEVELS.DEV }, ); /** Applies a moderation action, mirroring what the slash commands do (M8). */ router.post( '/api/discord/moderation', async ({ context, body, actor }) => { const guild = guildOf(context); const actorMember = await actingMember(guild, actor); const action = String(body.action ?? ''); if (!['warn', 'mute', 'kick', 'ban'].includes(action)) { throw badRequest('Action attendue : warn, mute, kick ou ban.'); } const member = await guild.members.fetch(String(body.userId ?? '')).catch(() => null); if (!member) throw notFound('Membre introuvable sur le serveur.'); if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); const reason = String(body.reason ?? '').trim() || 'Non précisé'; const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null; if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) { throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.'); } const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`; if (action === 'mute') await member.timeout(durationMs, audit); else if (action === 'kick') await member.kick(audit); else if (action === 'ban') await member.ban({ reason: audit, deleteMessageSeconds: 0 }); recordAction({ guildId: guild.id, action, moderatorId: actor.userId, targetId: member.id, reason, durationMs, }); logEvent({ guildId: guild.id, type: `moderation.${action}`, actorId: actor.userId, payload: { targetId: member.id, reason, durationMs, source: 'web' }, }); await sendModerationLog(context.client, guild, { action, targetId: member.id, moderatorId: actor.userId, reason, durationMs, }); return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action }; }, { access: ACCESS_LEVELS.STAFF }, ); router.get( '/api/discord/moderation', ({ query }) => ({ actions: listActions({ guildId: guildId(), targetId: query.get('userId'), action: query.get('action'), limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200), }), totals: countByAction(guildId()), }), { access: ACCESS_LEVELS.STAFF }, ); /** Publishes a message in a channel: announcements, maintenance notices. */ router.post( '/api/discord/announce', async ({ context, body, actor }) => { const guild = guildOf(context); const channelId = String(body.channelId ?? '') || env.channels.announcements; if (!channelId) throw badRequest('Aucun salon de destination.'); const channel = await context.client.channels.fetch(channelId).catch(() => null); if (!channel?.isSendable()) throw badRequest('Salon introuvable ou non accessible en écriture.'); const content = String(body.content ?? '').trim(); const title = String(body.title ?? '').trim(); if (content === '' && title === '') throw badRequest('Le message est vide.'); const payload = body.asEmbed ? { embeds: [ { title: title || undefined, description: content || undefined, color: Number.parseInt(String(body.color ?? '0x1793d1'), 16) || 0x1793d1, footer: { text: `Publié par ${actor.displayName ?? actor.username}` }, timestamp: new Date().toISOString(), }, ], } : { content: title ? `**${title}**\n${content}` : content }; const message = await channel.send(payload); logEvent({ guildId: guild.id, type: 'web.announce', actorId: actor.userId, payload: { channelId, messageId: message.id }, }); log.info('Announcement published from the dashboard', { channelId, actor: actor.userId }); return { ok: true, messageId: message.id, url: message.url }; }, { access: ACCESS_LEVELS.STAFF }, ); // --- Notification routing -------------------------------------------------- router.get( '/api/discord/notifications', () => ({ overrides: listNotificationChannels(guildId()), defaults: { issues: env.channels.notifIssues, pull_requests: env.channels.notifPullRequests, commits: env.channels.notifCommits, releases: env.channels.notifReleases, errors: env.channels.notifErrors, announcements: env.channels.announcements, community: env.channels.logs, }, }), { access: ACCESS_LEVELS.STAFF }, ); router.put( '/api/discord/notifications/:type', ({ params, body, actor }) => { const channelId = String(body.channelId ?? '').trim(); if (channelId === '') { removeNotificationChannel(guildId(), params.type); return { ok: true, removed: true }; } if (!/^\d{17,20}$/.test(channelId)) throw badRequest('Identifiant de salon invalide.'); setNotificationChannel({ guildId: guildId(), type: params.type, channelId, detailLevel: String(body.detailLevel ?? 'normal'), }); logEvent({ guildId: guildId(), type: 'web.notifications.update', actorId: actor.userId, payload: { type: params.type, channelId }, }); return { ok: true }; }, { access: ACCESS_LEVELS.STAFF }, ); /** * Publishes the slash commands on the guild, what `npm run deploy:commands` * does. Guild commands take effect immediately, so the result is visible in * Discord as soon as this returns. */ router.post( '/api/discord/commands/deploy', async ({ context, actor }) => { const commands = [...(context.client?.commands?.values() ?? [])]; if (commands.length === 0) throw badRequest('Aucune commande chargée : le bot n’est pas prêt.'); if (!env.discord.token || !env.discord.clientId || !env.discord.guildId) { throw badRequest('`DISCORD_TOKEN`, `DISCORD_CLIENT_ID` et `DISCORD_GUILD_ID` sont requis.'); } const body = commands.map((command) => command.data.toJSON()); const rest = new REST().setToken(env.discord.token); try { await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body, }); } catch (error) { log.error('Slash command deployment failed', error); throw new ExternalApiError('discord', error.message ?? 'Publication refusée par Discord'); } logEvent({ guildId: guildId(), type: 'web.commands.deploy', actorId: actor.userId, payload: { count: body.length }, }); log.info('Slash commands deployed from the dashboard', { count: body.length, actor: actor.userId }); return { ok: true, count: body.length, names: body.map((command) => command.name).sort() }; }, { access: ACCESS_LEVELS.OWNER }, ); /** Read-only inventory of the loaded slash commands and their required level. */ router.get( '/api/discord/commands', ({ context }) => ({ commands: [...(context.client?.commands?.values() ?? [])] .map((command) => { // `toJSON()` flattens the builder, whose option objects are builders too. const definition = command.data.toJSON(); return { name: definition.name, description: definition.description, access: command.access ?? ACCESS_LEVELS.USER, accessLabel: ACCESS_LABELS[command.access ?? ACCESS_LEVELS.USER], subcommandAccess: command.subcommandAccess ?? null, options: (definition.options ?? []).map((option) => ({ name: option.name, description: option.description, type: option.type, })), }; }) .sort((a, b) => a.name.localeCompare(b.name)), }), { access: ACCESS_LEVELS.STAFF }, ); }