feat(web): expose the dashboard API
One module per domain, each route declaring the minimum access level the server enforces before the handler runs. Irreversible actions ask for the exact name to be typed back, and every write lands in `event_logs` with its author so the history says who did what. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
11 files changed
+2713
No files matched your search
@@ -0,0 +1,366 @@
|
||||
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 { getSetting, setSetting } from '../../database/repositories/settings-repository.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;
|
||||
|
||||
/** Guild settings the dashboard exposes as first-class switches. */
|
||||
const MANAGED_SETTINGS = Object.freeze([
|
||||
{
|
||||
key: 'welcome.enabled',
|
||||
label: 'Message de bienvenue',
|
||||
help: 'Publier un message dans le salon d’accueil à chaque arrivée.',
|
||||
type: 'bool',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
key: 'welcome.directMessage',
|
||||
label: 'Message privé de bienvenue',
|
||||
help: 'Envoyer en plus un message privé au nouveau membre.',
|
||||
type: 'bool',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
key: 'departure.announce',
|
||||
label: 'Annoncer les départs',
|
||||
help: 'Publier une ligne dans les logs quand un membre quitte le serveur.',
|
||||
type: 'bool',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
key: 'moderation.dmTarget',
|
||||
label: 'Prévenir le membre sanctionné',
|
||||
help: 'Envoyer un message privé expliquant la sanction et son motif.',
|
||||
type: 'bool',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
key: 'tickets.autoClaim',
|
||||
label: 'Prise en charge automatique',
|
||||
help: 'Attribuer le ticket à la première personne du staff qui y écrit.',
|
||||
type: 'bool',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
key: 'deploy.requireConfirmation',
|
||||
label: 'Confirmation avant déploiement',
|
||||
help: 'Demander de retaper le nom de l’environnement avant de lancer un déploiement.',
|
||||
type: 'bool',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
key: 'web.defaultMode',
|
||||
label: 'Mode d’affichage par défaut',
|
||||
help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages).',
|
||||
type: 'enum',
|
||||
options: ['simple', 'advanced'],
|
||||
default: 'simple',
|
||||
},
|
||||
]);
|
||||
|
||||
const readManaged = () =>
|
||||
Object.fromEntries(
|
||||
MANAGED_SETTINGS.map((setting) => {
|
||||
try {
|
||||
return [setting.key, getSetting(guildId(), setting.key, setting.default)];
|
||||
} catch {
|
||||
return [setting.key, setting.default];
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export function registerSettingsRoutes(router) {
|
||||
router.get(
|
||||
'/api/settings',
|
||||
({ actor }) => ({
|
||||
schema: MANAGED_SETTINGS,
|
||||
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(),
|
||||
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 }) => {
|
||||
const schema = MANAGED_SETTINGS.find((setting) => setting.key === params.key);
|
||||
if (!schema) throw notFound('Réglage inconnu.');
|
||||
|
||||
let value = body.value;
|
||||
if (schema.type === 'bool') value = Boolean(value);
|
||||
else if (schema.type === 'enum') {
|
||||
value = String(value);
|
||||
if (!schema.options.includes(value))
|
||||
throw badRequest(`Valeurs possibles : ${schema.options.join(', ')}.`);
|
||||
}
|
||||
|
||||
setSetting(guildId(), schema.key, value, actor.userId);
|
||||
logEvent({
|
||||
guildId: guildId(),
|
||||
type: 'web.settings.update',
|
||||
actorId: actor.userId,
|
||||
payload: { key: schema.key, value },
|
||||
});
|
||||
return { key: schema.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 },
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user