import { randomBytes } from 'node:crypto'; import { mkdirSync } from 'node:fs'; import path from 'node:path'; import { ACCESS_LABELS, ACCESS_LEVELS, NOTIFICATION_TYPES, TICKET_CATEGORIES, } from '../../config/constants.js'; import { env } from '../../config/env.js'; import { createLogger } from '../../core/logger.js'; import { getDatabase } from '../../database/index.js'; import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js'; import { GUILD_SETTINGS, SETTING_SECTIONS, allSettings, writeSetting } from '../../config/guild-settings.js'; import { createApiToken, deleteSession, listApiTokens, listSessions, purgeExpiredSessions, revokeApiToken, } from '../../database/repositories/web-session-repository.js'; import { org } from '../../services/gitea/gitea-admin.js'; import { isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { badRequest, forbidden, notFound } from '../http.js'; import { hashToken } from '../auth/session.js'; import { isOauthConfigured, redirectUri } from '../auth/discord-oauth.js'; /** Everything the settings tab needs (M16-T10). */ const log = createLogger('web:settings'); const guildId = () => env.discord.guildId; const readManaged = () => { try { return allSettings(guildId()); } catch { // The database is not ready: fall back to the declared defaults. return Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting.default])); } }; export function registerSettingsRoutes(router) { router.get( '/api/settings', ({ request, actor }) => ({ schema: GUILD_SETTINGS, sections: SETTING_SECTIONS, values: readManaged(), runtime: { nodeEnv: env.nodeEnv, logLevel: env.logLevel, logDir: env.logDir, logRetentionDays: env.logRetentionDays, databasePath: env.database.path, backupDir: env.database.backupDir, nodeVersion: process.version, pid: process.pid, }, discord: { clientId: env.discord.clientId, guildId: env.discord.guildId, roles: env.roles, channels: env.channels, tokenConfigured: Boolean(env.discord.token), }, gitea: { configured: isGiteaConfigured(), url: env.gitea.url, owner: env.gitea.owner, repo: env.gitea.repo, repositoryUrl: repositoryUrl(), timeoutMs: env.gitea.timeoutMs, maxRetries: env.gitea.maxRetries, tokenConfigured: Boolean(env.gitea.token), }, webhook: { enabled: env.webhook.enabled, host: env.webhook.host, port: env.webhook.port, path: env.webhook.path, secretConfigured: Boolean(env.webhook.secret), publicUrl: env.web.publicUrl ? `${env.web.publicUrl}${env.webhook.path}` : null, }, web: { enabled: env.web.enabled, host: env.web.host, port: env.web.port, publicUrl: env.web.publicUrl, sessionTtlHours: env.web.sessionTtlHours, oauthConfigured: isOauthConfigured(), redirectUri: redirectUri(request), allowCommandDeploys: env.web.allowCommandDeploys, allowRestart: env.web.allowRestart, rateLimitPerMinute: env.web.rateLimitPerMinute, }, reference: { notificationTypes: NOTIFICATION_TYPES, ticketCategories: TICKET_CATEGORIES, accessLevels: Object.entries(ACCESS_LEVELS).map(([name, value]) => ({ name, value, label: ACCESS_LABELS[value], })), }, viewer: { accessLevel: actor.accessLevel, accessLabel: ACCESS_LABELS[actor.accessLevel] }, }), { access: ACCESS_LEVELS.STAFF }, ); router.put( '/api/settings/values/:key', ({ params, body, actor }) => { if (!GUILD_SETTINGS.some((setting) => setting.key === params.key)) throw notFound('Réglage inconnu.'); let value; try { value = writeSetting(params.key, body.value, { guildId: guildId(), updatedBy: actor.userId }); } catch (error) { throw badRequest(error.message); } logEvent({ guildId: guildId(), type: 'web.settings.update', actorId: actor.userId, payload: { key: params.key, value }, }); return { key: params.key, value }; }, { access: ACCESS_LEVELS.DEV }, ); // --- Sessions -------------------------------------------------------------- router.get( '/api/settings/sessions', ({ actor }) => ({ sessions: listSessions().map((session) => ({ ...session, accessLabel: ACCESS_LABELS[session.access_level], current: session.id === actor.sessionId, })), }), { access: ACCESS_LEVELS.OWNER }, ); router.delete( '/api/settings/sessions/:id', ({ params, actor }) => { if (params.id === actor.sessionId) throw badRequest('Utilise la déconnexion pour fermer ta propre session.'); const removed = deleteSession(params.id); if (removed === 0) throw notFound('Session introuvable.'); return { ok: true }; }, { access: ACCESS_LEVELS.OWNER }, ); // --- API tokens ------------------------------------------------------------ router.get( '/api/settings/tokens', () => ({ tokens: listApiTokens().map((token) => ({ ...token, accessLabel: ACCESS_LABELS[token.access_level], active: !token.revoked_at, })), }), { access: ACCESS_LEVELS.OWNER }, ); /** The clear token is shown once and never stored, only its hash is kept. */ router.post( '/api/settings/tokens', ({ body, actor }) => { const name = String(body.name ?? '').trim(); if (!/^[\w .-]{3,60}$/.test(name)) throw badRequest('Nom de jeton invalide (3 à 60 caractères).'); const accessLevel = Number.parseInt(body.accessLevel ?? ACCESS_LEVELS.STAFF, 10); if (!Object.values(ACCESS_LEVELS).includes(accessLevel)) throw badRequest('Niveau d’accès inconnu.'); if (accessLevel > actor.accessLevel) throw forbidden('Tu ne peux pas créer un jeton plus puissant que toi.'); const token = `fws_${randomBytes(24).toString('base64url')}`; const id = createApiToken({ name, tokenHash: hashToken(token), prefix: token.slice(0, 12), accessLevel, createdBy: actor.userId, expiresAt: body.expiresAt ? String(body.expiresAt) : null, }); logEvent({ guildId: guildId(), type: 'web.token.create', actorId: actor.userId, payload: { id, name, accessLevel }, }); return { id, name, accessLevel, token }; }, { access: ACCESS_LEVELS.OWNER }, ); router.delete( '/api/settings/tokens/:id', ({ params, actor }) => { const revoked = revokeApiToken(Number.parseInt(params.id, 10)); if (revoked === 0) throw notFound('Jeton introuvable ou déjà révoqué.'); logEvent({ guildId: guildId(), type: 'web.token.revoke', actorId: actor.userId, payload: { id: params.id }, }); return { ok: true }; }, { access: ACCESS_LEVELS.OWNER }, ); // --- Maintenance ----------------------------------------------------------- router.post( '/api/settings/backup', ({ actor }) => { mkdirSync(env.database.backupDir, { recursive: true }); const file = path.join( env.database.backupDir, `fws-bot-${new Date().toISOString().replace(/[:.]/g, '-')}.sqlite`, ); // `VACUUM INTO` produces a consistent copy even with the WAL journal active. getDatabase().exec(`VACUUM INTO '${file.replaceAll("'", "''")}'`); logEvent({ guildId: guildId(), type: 'web.backup', actorId: actor.userId, payload: { file } }); log.info('Database backup written', { file }); return { file }; }, { access: ACCESS_LEVELS.OWNER }, ); router.post( '/api/settings/purge', ({ body, actor }) => { const days = Number.parseInt(body.days ?? env.logRetentionDays, 10); if (!Number.isInteger(days) || days < 1) throw badRequest('Nombre de jours invalide.'); const events = purgeEventsOlderThan(days); const sessions = purgeExpiredSessions(); logEvent({ guildId: guildId(), type: 'web.purge', actorId: actor.userId, payload: { days, events, sessions }, }); return { events, sessions }; }, { access: ACCESS_LEVELS.OWNER }, ); /** Checks the credentials without revealing them. */ router.post( '/api/settings/test/:service', async ({ params, context }) => { if (params.service === 'discord') { const client = context.client; return { ok: Boolean(client?.isReady?.()), detail: client?.isReady?.() ? `Connecté en tant que ${client.user.tag}, ping ${client.ws.ping} ms.` : 'Le bot n’est pas connecté à Discord.', }; } if (params.service === 'gitea') { if (!isGiteaConfigured()) return { ok: false, detail: 'GITEA_URL ou GITEA_TOKEN manquant.' }; try { const user = await org.whoami(); const organization = await org.get().catch(() => null); return { ok: true, detail: `Jeton valide pour « ${user.login} »${organization ? `, accès à l’organisation « ${organization.username ?? organization.name} »` : ', mais l’organisation est inaccessible'}.`, }; } catch (error) { return { ok: false, detail: `Échec de l’appel Gitea : ${error.message}` }; } } throw notFound('Service inconnu.'); }, { access: ACCESS_LEVELS.STAFF }, ); /** * Stops the process so a supervisor restarts it. Without one, the bot simply * stops, which is why the capability is disabled by default. */ router.post( '/api/settings/restart', ({ actor }) => { if (!env.web.allowRestart) throw forbidden('Le redémarrage est désactivé (`WEB_ALLOW_RESTART`).'); logEvent({ guildId: guildId(), type: 'web.restart', actorId: actor.userId, payload: null }); log.warn('Restart requested from the dashboard', { actor: actor.userId }); setTimeout(() => process.exit(0), 500).unref(); return { ok: true, message: 'Redémarrage dans un instant…' }; }, { access: ACCESS_LEVELS.OWNER }, ); }