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:
nocodeandClaude Opus 5 committed 2026-09-23 20:09:13 +02:00
1 parent 611129b23c
commit bf92badb05
11 files changed
+2713

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { countVotes, listPolls } from '../../database/repositories/poll-repository.js';
import { closeTicket, listTickets } from '../../database/repositories/ticket-repository.js';
import { listVoiceChannels } from '../../database/repositories/voice-repository.js';
import { listBotStatuses } from '../../database/repositories/bot-status-repository.js';
import { closePollById } from '../../services/polls/poll-service.js';
import {
addBotStatus,
applyStatusIfAlone,
clampRotation,
getRotationSeconds,
removeBotStatus,
saveRotationSeconds,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import {
deleteVoiceChannel,
listTriggerSummaries,
removeVoiceTriggerConfig,
saveVoiceTrigger,
setTriggerEnabled,
} from '../../services/voice/voice-service.js';
import { badRequest, notFound } from '../http.js';
/** Tickets, polls, temporary voice channels and bot presence (M16-T05). */
const guildId = () => env.discord.guildId;
export function registerCommunityRoutes(router) {
// --- Tickets ---------------------------------------------------------------
router.get(
'/api/community/tickets',
({ query }) => ({
categories: TICKET_CATEGORIES,
tickets: listTickets({
guildId: guildId(),
status: query.get('status'),
authorId: query.get('authorId'),
limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200),
}),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/tickets/:id/close',
async ({ params, body, actor, context }) => {
const id = Number.parseInt(params.id, 10);
const reason = String(body.reason ?? '').trim() || 'Clôturé depuis le tableau de bord';
const changes = closeTicket(id, { closedBy: actor.userId, reason });
if (changes === 0) throw notFound('Ticket introuvable ou déjà clôturé.');
const ticket = listTickets({ guildId: guildId(), limit: 200 }).find((row) => row.id === id);
if (ticket?.channel_id && context.client) {
const channel = await context.client.channels.fetch(ticket.channel_id).catch(() => null);
await channel?.delete(`Ticket #${id} clôturé depuis le tableau de bord`).catch(() => null);
}
logEvent({ guildId: guildId(), type: 'ticket.close', actorId: actor.userId, payload: { id, reason } });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Polls -----------------------------------------------------------------
router.get(
'/api/community/polls',
({ query }) => ({
polls: listPolls({
guildId: guildId(),
status: query.get('status'),
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100),
}).map((poll) => ({
...poll,
choices: JSON.parse(poll.choices),
counts: countVotes(poll.id),
})),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/polls/:id/close',
async ({ params, actor, context }) => {
// `closePollById` raises a `UserFacingError` when the poll is gone or already closed.
const id = Number.parseInt(params.id, 10);
await closePollById(context.client, id);
logEvent({ guildId: guildId(), type: 'poll.close', actorId: actor.userId, payload: { id } });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Temporary voice channels ---------------------------------------------
router.get(
'/api/community/voice',
({ context }) => {
const guild = context.client?.guilds?.cache?.get(guildId());
return {
triggers: listTriggerSummaries(guildId()),
channels: listVoiceChannels(guildId()).map((row) => {
const channel = guild?.channels?.cache?.get(row.channel_id);
return {
...row,
locked: Boolean(row.locked),
alive: Boolean(channel),
members: channel?.members?.size ?? 0,
};
}),
defaults: {
triggerId: env.channels.voiceTrigger,
categoryId: env.channels.voiceCategory,
emptyGraceMs: env.voice.emptyGraceMs,
},
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.put(
'/api/community/voice/triggers/:triggerId',
({ params, body, actor }) => {
if (!/^\d{17,20}$/.test(params.triggerId)) throw badRequest('Identifiant de salon invalide.');
const trigger = saveVoiceTrigger(
guildId(),
{
triggerId: params.triggerId,
label: body.label === undefined ? undefined : String(body.label),
categoryId: body.categoryId === undefined ? undefined : String(body.categoryId),
template: body.template === undefined ? undefined : String(body.template),
userLimit: body.userLimit === undefined ? undefined : Number.parseInt(body.userLimit, 10),
},
actor.userId,
);
return { trigger };
},
{ access: ACCESS_LEVELS.DEV },
);
router.post(
'/api/community/voice/triggers/:triggerId/toggle',
({ params, body }) => ({
trigger: setTriggerEnabled(guildId(), params.triggerId, Boolean(body.enabled)),
}),
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/voice/triggers/:triggerId',
({ params }) => {
removeVoiceTriggerConfig(guildId(), params.triggerId);
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/voice/channels/:channelId',
async ({ params, context, actor }) => {
const channel = await context.client?.channels?.fetch(params.channelId).catch(() => null);
if (!channel) throw notFound('Salon introuvable.');
await deleteVoiceChannel(channel, `Supprimé depuis le tableau de bord par ${actor.username}`);
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Bot presence ----------------------------------------------------------
router.get(
'/api/community/statuses',
() => ({
statuses: listBotStatuses(),
intervalSeconds: getRotationSeconds(guildId()),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/statuses',
({ body, actor, context }) => {
const status = addBotStatus({
text: String(body.text ?? ''),
type: String(body.type ?? 'watching'),
url: body.url ? String(body.url) : null,
createdBy: actor.userId,
});
// Applies straight away when it is the only status, like `/status add` does.
if (context.client) applyStatusIfAlone(context.client);
return { status };
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/community/statuses/:id',
// The service raises a `UserFacingError` for an unknown id or a no-op toggle.
({ params, body }) => ({
status: toggleBotStatus(Number.parseInt(params.id, 10), Boolean(body.enabled)),
}),
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/statuses/:id',
({ params }) => ({ removed: removeBotStatus(Number.parseInt(params.id, 10)) }),
{ access: ACCESS_LEVELS.DEV },
);
router.put(
'/api/community/statuses/interval',
({ body, actor }) => {
const seconds = clampRotation(Number.parseInt(body.seconds ?? 0, 10), { strict: true });
saveRotationSeconds(seconds, guildId(), actor.userId);
return { intervalSeconds: seconds, restartRequired: true };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+224
View File
@@ -0,0 +1,224 @@
import { randomBytes } from 'node:crypto';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { badRequest, notFound } from '../http.js';
import {
diffValues,
maskValues,
mergeValues,
readEnvFile,
renderEnvFile,
secretStatus,
writeEnvFile,
} from '../services/env-file.js';
import { SECTIONS, VARIABLES, crossCheck, requiredKeys, validateAll } from '../services/env-schema.js';
/**
* Step by step `.env` wizard (M16-T09).
*
* Reachable by a bootstrap session, because its whole purpose is to run before
* the bot has a working configuration.
*/
const log = createLogger('web:configuration');
const WIZARD = { access: ACCESS_LEVELS.OWNER, setup: true };
/** Values currently loaded in the process, used to prefill a first run. */
const runningValues = () => ({
NODE_ENV: env.nodeEnv,
LOG_LEVEL: env.logLevel,
LOG_DIR: env.logDir,
LOG_RETENTION_DAYS: String(env.logRetentionDays),
DISCORD_CLIENT_ID: env.discord.clientId,
DISCORD_GUILD_ID: env.discord.guildId,
GITEA_URL: env.gitea.url,
GITEA_OWNER: env.gitea.owner,
GITEA_REPO: env.gitea.repo,
DATABASE_PATH: env.database.path,
});
function currentValues() {
const file = readEnvFile();
const defaults = Object.fromEntries(
VARIABLES.filter((variable) => variable.default !== undefined).map((v) => [v.key, v.default]),
);
return { file, values: { ...defaults, ...runningValues(), ...file.values } };
}
function report(values) {
const errors = validateAll(values);
const missing = requiredKeys().filter((key) => !String(values[key] ?? '').trim());
return {
errors,
warnings: crossCheck(values),
missingRequired: missing,
valid: Object.keys(errors).length === 0,
};
}
export function registerConfigurationRoutes(router) {
router.get(
'/api/configuration',
() => {
const { file, values } = currentValues();
return {
sections: SECTIONS,
variables: VARIABLES,
exists: file.exists,
unknownKeys: Object.keys(file.unknown),
values: maskValues(values),
secrets: secretStatus(values),
...report(values),
};
},
WIZARD,
);
/** Live feedback while the form is being filled, nothing is written. */
router.post(
'/api/configuration/validate',
({ body }) => {
const { values } = currentValues();
const next = mergeValues(values, body.values ?? {});
return { ...report(next), diff: diffValues(values, next) };
},
WIZARD,
);
router.post(
'/api/configuration/preview',
({ body }) => {
const { file, values } = currentValues();
const next = mergeValues(values, body.values ?? {});
// Secrets are blanked out: the preview may be copied or screenshotted.
const safe = { ...next };
for (const variable of VARIABLES) {
if (variable.type === 'secret' && safe[variable.key]) safe[variable.key] = '••••••••';
}
return { content: renderEnvFile(safe, file.unknown) };
},
WIZARD,
);
router.post(
'/api/configuration/save',
({ body, actor }) => {
const { file, values } = currentValues();
const next = mergeValues(values, body.values ?? {});
const status = report(next);
// A partial save is allowed while the wizard is still being walked through,
// but a malformed value never reaches the file.
if (!status.valid && body.force !== true) {
throw badRequest('Certaines valeurs sont invalides.', status.errors);
}
const diff = diffValues(values, next);
if (diff.length === 0) return { ...status, diff, written: false };
const { backup } = writeEnvFile(next, { unknown: file.unknown });
log.info('Configuration saved from the wizard', {
actor: actor.userId ?? 'setup',
changed: diff.map((entry) => entry.key),
});
return {
...status,
diff,
written: true,
backup,
restartRequired: diff.some((entry) => entry.restartRequired),
};
},
WIZARD,
);
router.post(
'/api/configuration/generate',
({ body }) => {
const kind = String(body.kind ?? 'hex32');
const sizes = { hex16: 16, hex32: 32 };
if (!(kind in sizes)) throw badRequest('Type de secret inconnu.');
return { value: randomBytes(sizes[kind]).toString('hex') };
},
WIZARD,
);
/**
* Tries the credentials the user just typed, before they are written to disk.
* Nothing is stored and the value never appears in the response.
*/
router.post(
'/api/configuration/test/:service',
async ({ params, body }) => {
const values = mergeValues(currentValues().values, body.values ?? {});
if (params.service === 'discord') {
const token = String(values.DISCORD_TOKEN ?? '');
if (!token) return { ok: false, detail: 'Aucun token à tester.' };
try {
const response = await fetch('https://discord.com/api/v10/users/@me', {
headers: { Authorization: `Bot ${token}` },
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) {
return {
ok: false,
detail:
response.status === 401
? 'Token refusé par Discord. Vérifie que tu as bien copié le token du bot (et non le client secret).'
: `Discord a répondu ${response.status}.`,
};
}
const user = await response.json();
return {
ok: true,
detail: `Token valide : ${user.username} (${user.id}).`,
applicationId: user.id,
};
} catch (error) {
return { ok: false, detail: `Discord injoignable : ${error.message}` };
}
}
if (params.service === 'gitea') {
const url = String(values.GITEA_URL ?? '').replace(/\/+$/, '');
const token = String(values.GITEA_TOKEN ?? '');
if (!url || !token) return { ok: false, detail: 'URL ou jeton manquant.' };
try {
const response = await fetch(`${url}/api/v1/user`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) return { ok: false, detail: `Gitea a répondu ${response.status}.` };
const user = await response.json();
const owner = String(values.GITEA_OWNER ?? '');
let detail = `Jeton valide pour « ${user.login} ».`;
let organizationReachable = true;
if (owner) {
const orgResponse = await fetch(`${url}/api/v1/orgs/${encodeURIComponent(owner)}`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
organizationReachable = orgResponse.ok;
detail += orgResponse.ok
? ` Organisation « ${owner} » accessible.`
: ` En revanche l’organisation « ${owner} » est inaccessible (${orgResponse.status}).`;
}
// The token itself works: an unreachable organization is a warning, not a failure.
return { ok: true, warning: !organizationReachable, detail };
} catch (error) {
return { ok: false, detail: `Gitea injoignable : ${error.message}` };
}
}
throw notFound('Service inconnu.');
},
WIZARD,
);
}
+254
View File
@@ -0,0 +1,254 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import {
createTarget,
getDeployment,
getTarget,
listDeployments,
listTargets,
removeTarget,
updateTarget,
} from '../../database/repositories/deploy-repository.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { splitRepository } from '../../services/gitea/gitea-admin.js';
import { badRequest, forbidden, notFound } from '../http.js';
import { assertRunnable, describeTarget, runDeployment } from '../services/deploy-service.js';
/** Deploy targets and deployment history (M16-T06 / M16-T07). */
const KINDS = ['webhook', 'command', 'gitea-action'];
const guildId = () => env.discord.guildId;
/** A target's config may hold a shared secret, which never leaves the server. */
const publicTarget = (target) => ({
id: target.id,
name: target.name,
repository: target.repository,
environment: target.environment,
kind: target.kind,
autoDeploy: target.auto_deploy,
enabled: target.enabled,
summary: describeTarget(target),
config: {
url: target.config.url ?? null,
method: target.config.method ?? null,
command: target.config.command ?? null,
cwd: target.config.cwd ?? null,
workflow: target.config.workflow ?? null,
ref: target.config.ref ?? null,
hasSecret: Boolean(target.config.secret),
},
createdBy: target.created_by,
createdAt: target.created_at,
updatedAt: target.updated_at,
});
function readTargetPayload(body, { partial = false } = {}) {
const config = {};
const payload = {};
const kind = body.kind === undefined && partial ? undefined : String(body.kind ?? '');
if (kind !== undefined) {
if (!KINDS.includes(kind)) throw badRequest(`Type de cible attendu : ${KINDS.join(', ')}.`);
payload.kind = kind;
}
if (body.name !== undefined) {
const name = String(body.name).trim();
if (!/^[\w .-]{2,60}$/.test(name)) throw badRequest('Nom de cible invalide (2 à 60 caractères).');
payload.name = name;
}
if (body.repository !== undefined) {
const repository = String(body.repository).trim();
if (!splitRepository(repository)) throw badRequest('Dépôt attendu au format `organisation/depot`.');
payload.repository = repository;
}
if (body.environment !== undefined) {
const environment = String(body.environment).trim();
if (!/^[\w-]{2,30}$/.test(environment)) throw badRequest('Nom d’environnement invalide.');
payload.environment = environment;
}
if (body.autoDeploy !== undefined) payload.auto_deploy = Boolean(body.autoDeploy);
if (body.enabled !== undefined) payload.enabled = Boolean(body.enabled);
if (body.config && typeof body.config === 'object') {
const source = body.config;
if (source.url !== undefined) {
const url = String(source.url).trim();
if (url && !/^https?:\/\//.test(url)) throw badRequest('L’URL du webhook doit être en http(s).');
config.url = url;
}
if (source.method !== undefined) {
const method = String(source.method).toUpperCase();
if (!['POST', 'PUT', 'PATCH'].includes(method)) throw badRequest('Méthode HTTP non autorisée.');
config.method = method;
}
if (source.secret !== undefined) config.secret = String(source.secret);
if (source.headers !== undefined && typeof source.headers === 'object') config.headers = source.headers;
if (source.command !== undefined) config.command = String(source.command);
if (source.cwd !== undefined) config.cwd = String(source.cwd);
if (source.workflow !== undefined) config.workflow = String(source.workflow);
if (source.ref !== undefined) config.ref = String(source.ref);
if (source.inputs !== undefined && typeof source.inputs === 'object') config.inputs = source.inputs;
payload.config = config;
}
return payload;
}
/** Command targets execute shell on the host, so they stay Owner-only. */
function assertMayManage(actor, kind) {
if (kind !== 'command') return;
if (!env.web.allowCommandDeploys) {
throw forbidden('Les cibles de type commande sont désactivées (`WEB_ALLOW_COMMAND_DEPLOYS`).');
}
if (actor.accessLevel < ACCESS_LEVELS.OWNER) {
throw forbidden('Seul le niveau Owner peut gérer une cible de type commande.');
}
}
export function registerDeploymentRoutes(router) {
router.get(
'/api/deploy/targets',
({ query }) => ({
targets: listTargets({ guildId: guildId(), repository: query.get('repository') }).map(publicTarget),
commandDeploysAllowed: env.web.allowCommandDeploys,
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/deploy/targets',
({ body, actor }) => {
const payload = readTargetPayload(body);
if (!payload.name || !payload.repository || !payload.kind) {
throw badRequest('`name`, `repository` et `kind` sont obligatoires.');
}
assertMayManage(actor, payload.kind);
const target = createTarget({
guildId: guildId(),
name: payload.name,
repository: payload.repository,
environment: payload.environment ?? 'production',
kind: payload.kind,
config: payload.config ?? {},
autoDeploy: payload.auto_deploy ?? false,
enabled: payload.enabled ?? true,
createdBy: actor.userId,
});
logEvent({
guildId: guildId(),
type: 'web.deploy.target.create',
actorId: actor.userId,
payload: { name: target.name, kind: target.kind },
});
return publicTarget(target);
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/deploy/targets/:id',
({ params, body, actor }) => {
const current = getTarget(Number.parseInt(params.id, 10));
if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.');
const payload = readTargetPayload(body, { partial: true });
assertMayManage(actor, payload.kind ?? current.kind);
// A partial config patch must not wipe the secret already stored.
if (payload.config) payload.config = { ...current.config, ...payload.config };
const updated = updateTarget(current.id, payload);
logEvent({
guildId: guildId(),
type: 'web.deploy.target.update',
actorId: actor.userId,
payload: { name: updated.name },
});
return publicTarget(updated);
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/deploy/targets/:id',
({ params, actor }) => {
const current = getTarget(Number.parseInt(params.id, 10));
if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.');
removeTarget(current.id);
logEvent({
guildId: guildId(),
type: 'web.deploy.target.delete',
actorId: actor.userId,
payload: { name: current.name },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
/** Dry run: checks the target without contacting anything. */
router.post(
'/api/deploy/targets/:id/check',
({ params }) => {
const target = getTarget(Number.parseInt(params.id, 10));
if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.');
try {
assertRunnable(target);
return { ok: true, summary: describeTarget(target) };
} catch (error) {
return { ok: false, reason: error.message };
}
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/deploy/targets/:id/run',
async ({ params, body, actor, context }) => {
const target = getTarget(Number.parseInt(params.id, 10));
if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.');
assertMayManage(actor, target.kind);
const deployment = await runDeployment(context.client, target, {
ref: body.ref ? String(body.ref) : null,
releaseTag: body.releaseTag ? String(body.releaseTag) : null,
source: 'web',
triggeredBy: actor.userId,
});
return deployment;
},
{ access: ACCESS_LEVELS.DEV },
);
router.get(
'/api/deployments',
({ query }) => ({
deployments: listDeployments({
guildId: guildId(),
repository: query.get('repository'),
status: query.get('status'),
targetId: query.get('targetId') ? Number.parseInt(query.get('targetId'), 10) : null,
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100),
}),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/deployments/:id',
({ params }) => {
const deployment = getDeployment(Number.parseInt(params.id, 10));
if (!deployment || deployment.guild_id !== guildId()) throw notFound('Déploiement introuvable.');
return deployment;
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+364
View File
@@ -0,0 +1,364 @@
import { ChannelType } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.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 },
);
/** 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 },
);
}
+47
View File
@@ -0,0 +1,47 @@
import { registerAuthRoutes } from '../auth/routes.js';
import { registerCommunityRoutes } from './community.js';
import { registerConfigurationRoutes } from './configuration.js';
import { registerDeploymentRoutes } from './deployments.js';
import { registerDiscordRoutes } from './discord.js';
import { registerLogRoutes } from './logs.js';
import { registerOrganizationRoutes } from './organization.js';
import { registerOverviewRoutes } from './overview.js';
import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js';
import { registerSettingsRoutes } from './settings.js';
/**
* Route registration order matters only for readability: the router matches on
* the full pattern, not on declaration order.
*/
export function registerApiRoutes(router, { setupOnly = false } = {}) {
// Liveness probe for a reverse proxy or an uptime monitor. Registered first so
// it answers even in bootstrap mode, when nothing else is mounted.
router.get(
'/api/health',
({ context }) => ({
status: context.client?.isReady?.() ? 'ok' : 'starting',
setupOnly: context.setupOnly,
uptimeMs: Date.now() - context.startedAt,
}),
{ public: true },
);
registerAuthRoutes(router);
registerConfigurationRoutes(router);
// In bootstrap mode the bot is not connected and the database may be empty:
// only the wizard makes sense.
if (setupOnly) return router;
registerOverviewRoutes(router);
registerOrganizationRoutes(router);
registerRepositoryRoutes(router);
registerReleaseRoutes(router);
registerDeploymentRoutes(router);
registerDiscordRoutes(router);
registerCommunityRoutes(router);
registerSettingsRoutes(router);
registerLogRoutes(router);
return router;
}
+96
View File
@@ -0,0 +1,96 @@
import { readFile, readdir, stat } from 'node:fs/promises';
import path from 'node:path';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { maskSecrets } from '../../core/logger.js';
import { getDatabase } from '../../database/index.js';
import { badRequest, notFound } from '../http.js';
/** Functional event log and technical log files (M16-T05). */
const LOG_FILE = /^\d{4}-\d{2}-\d{2}\.log$/;
export function registerLogRoutes(router) {
router.get(
'/api/logs/events',
({ query }) => {
const clauses = [];
const params = [];
const type = query.get('type');
if (type) {
clauses.push('type LIKE ?');
params.push(`${type}%`);
}
const actorId = query.get('actorId');
if (actorId) {
clauses.push('actor_id = ?');
params.push(actorId);
}
const limit = Math.min(Number.parseInt(query.get('limit') ?? '100', 10), 500);
params.push(limit);
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
const events = getDatabase()
.prepare(`SELECT * FROM event_logs ${where} ORDER BY id DESC LIMIT ?`)
.all(...params)
.map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null }));
return {
events,
types: getDatabase()
.prepare(
'SELECT type, COUNT(*) AS count FROM event_logs GROUP BY type ORDER BY count DESC LIMIT 40',
)
.all(),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/logs/files',
async () => {
const entries = await readdir(env.logDir).catch(() => []);
const files = [];
for (const name of entries.filter((entry) => LOG_FILE.test(entry))) {
const info = await stat(path.join(env.logDir, name)).catch(() => null);
if (info) files.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() });
}
return { directory: env.logDir, files: files.sort((a, b) => b.name.localeCompare(a.name)) };
},
{ access: ACCESS_LEVELS.DEV },
);
router.get(
'/api/logs/files/:name',
async ({ params, query }) => {
// The name pattern is the only thing standing between this route and the
// rest of the filesystem, so it is strict on purpose.
if (!LOG_FILE.test(params.name)) throw badRequest('Nom de fichier de log invalide.');
const content = await readFile(path.join(env.logDir, params.name), 'utf8').catch(() => null);
if (content === null) throw notFound('Fichier de log introuvable.');
const lines = Math.min(Number.parseInt(query.get('lines') ?? '300', 10), 2000);
const level = query.get('level');
const parsed = content
.split('\n')
.filter(Boolean)
.map((line) => {
try {
return JSON.parse(line);
} catch {
return { level: 'info', message: line };
}
})
.filter((entry) => !level || entry.level === level);
// `maskSecrets` already ran at write time; it runs again in case the file
// predates a secret rotation.
return { name: params.name, entries: JSON.parse(maskSecrets(JSON.stringify(parsed.slice(-lines)))) };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+179
View File
@@ -0,0 +1,179 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { org } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { badRequest } from '../http.js';
/** Organization-wide management (M16-T04). */
const requireGitea = () => {
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).');
};
const toMember = (member) => ({
id: member.id,
login: member.login ?? member.username,
fullName: member.full_name,
email: member.email,
avatar: member.avatar_url,
isAdmin: member.is_admin,
lastLogin: member.last_login,
createdAt: member.created,
});
export function registerOrganizationRoutes(router) {
router.get(
'/api/organization',
async () => {
requireGitea();
const [details, members, teams, repositories] = await Promise.all([
org.get(),
org.listMembers({ limit: 100 }).catch(() => []),
org.listTeams({ limit: 100 }).catch(() => []),
org.listRepos({ limit: 100 }).catch(() => []),
]);
return {
name: details.username ?? details.name,
fullName: details.full_name,
description: details.description,
website: details.website,
location: details.location,
email: details.email,
avatar: details.avatar_url,
visibility: details.visibility,
url: `${env.gitea.url}/${details.username ?? details.name}`,
members: members.map(toMember),
teams: teams.map((team) => ({
id: team.id,
name: team.name,
description: team.description,
permission: team.permission,
includesAllRepositories: team.includes_all_repositories,
canCreateOrgRepo: team.can_create_org_repo,
units: team.units,
})),
repositories: repositories.map((repository) => ({
id: repository.id,
fullName: repository.full_name,
name: repository.name,
description: repository.description,
private: repository.private,
archived: repository.archived,
fork: repository.fork,
template: repository.template,
defaultBranch: repository.default_branch,
stars: repository.stars_count,
forks: repository.forks_count,
watchers: repository.watchers_count,
openIssues: repository.open_issues_count,
openPulls: repository.open_pr_counter,
releases: repository.release_counter,
sizeKb: repository.size,
language: repository.language,
updatedAt: repository.updated_at,
createdAt: repository.created_at,
htmlUrl: repository.html_url,
hasIssues: repository.has_issues,
hasPullRequests: repository.has_pull_requests,
hasActions: repository.has_actions,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/organization',
async ({ body, actor }) => {
requireGitea();
const payload = {};
for (const field of ['full_name', 'description', 'website', 'location', 'visibility']) {
if (field in body) payload[field] = String(body[field] ?? '');
}
if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.');
await org.update(payload);
logEvent({
guildId: env.discord.guildId || null,
type: 'web.organization.update',
actorId: actor.userId,
payload: { fields: Object.keys(payload) },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.get(
'/api/organization/teams/:id/members',
async ({ params }) => {
requireGitea();
const members = await org.listTeamMembers(Number.parseInt(params.id, 10));
return { members: members.map(toMember) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/organization/labels',
async () => {
requireGitea();
return { labels: await org.listLabels() };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/organization/hooks',
async () => {
requireGitea();
const hooks = await org.listHooks().catch(() => []);
return {
hooks: hooks.map((hook) => ({
id: hook.id,
type: hook.type,
active: hook.active,
events: hook.events,
url: hook.config?.url,
createdAt: hook.created_at,
})),
};
},
{ access: ACCESS_LEVELS.DEV },
);
/** Creates a repository inside the organization (M16-T04). */
router.post(
'/api/organization/repositories',
async ({ body, actor }) => {
requireGitea();
const name = String(body.name ?? '').trim();
if (!/^[\w.-]{1,100}$/.test(name)) {
throw badRequest('Nom de dépôt invalide : lettres, chiffres, `.`, `-` et `_` uniquement.');
}
const created = await org.createRepo({
name,
description: String(body.description ?? ''),
private: Boolean(body.private),
auto_init: body.autoInit !== false,
default_branch: String(body.defaultBranch ?? 'main'),
gitignores: body.gitignores ?? undefined,
license: body.license ?? undefined,
readme: body.readme ?? undefined,
issue_labels: body.issueLabels ?? undefined,
});
logEvent({
guildId: env.discord.guildId || null,
type: 'web.repository.create',
actorId: actor.userId,
payload: { repository: created.full_name },
});
return { fullName: created.full_name, htmlUrl: created.html_url };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+158
View File
@@ -0,0 +1,158 @@
import { version as discordJsVersion } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { getDatabase } from '../../database/index.js';
import {
countByStatus,
lastDeploymentPerEnvironment,
} from '../../database/repositories/deploy-repository.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { countVoiceChannels } from '../../database/repositories/voice-repository.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { org } from '../../services/gitea/gitea-admin.js';
/** Aggregated landing page of the dashboard (M16-T05). */
const guildId = () => env.discord.guildId;
function botSnapshot(client, startedAt) {
const guild = client?.guilds?.cache?.get(guildId()) ?? null;
return {
online: Boolean(client?.isReady?.()),
username: client?.user?.username ?? null,
discriminator: client?.user?.discriminator ?? null,
avatar: client?.user?.displayAvatarURL?.({ size: 128 }) ?? null,
ping: client?.ws?.ping ?? null,
uptimeMs: Date.now() - startedAt,
nodeVersion: process.version,
discordJsVersion,
memoryMb: Math.round(process.memoryUsage().rss / 1024 / 1024),
commands: client?.commands?.size ?? 0,
guild: guild
? {
id: guild.id,
name: guild.name,
icon: guild.iconURL?.({ size: 128 }) ?? null,
memberCount: guild.memberCount,
channelCount: guild.channels.cache.size,
roleCount: guild.roles.cache.size,
boostTier: guild.premiumTier,
createdAt: guild.createdAt?.toISOString() ?? null,
}
: null,
};
}
function databaseSnapshot() {
const database = getDatabase();
const tables = database
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
.all()
.map((row) => row.name);
const counts = Object.fromEntries(
tables.map((table) => [table, database.prepare(`SELECT COUNT(*) AS count FROM "${table}"`).get().count]),
);
const pageCount = database.prepare('PRAGMA page_count').get();
const pageSize = database.prepare('PRAGMA page_size').get();
return {
path: env.database.path,
tables: counts,
sizeBytes: (pageCount?.page_count ?? 0) * (pageSize?.page_size ?? 0),
migrations: database.prepare('SELECT name, applied_at FROM schema_migrations ORDER BY name').all(),
};
}
async function giteaSnapshot() {
if (!isGiteaConfigured()) return { configured: false };
const [organization, repositories] = await Promise.all([
org.get().catch(() => null),
org.listRepos({ limit: 50 }).catch(() => []),
]);
const totals = repositories.reduce(
(accumulator, repository) => ({
openIssues: accumulator.openIssues + (repository.open_issues_count ?? 0),
openPulls: accumulator.openPulls + (repository.open_pr_counter ?? 0),
stars: accumulator.stars + (repository.stars_count ?? 0),
forks: accumulator.forks + (repository.forks_count ?? 0),
sizeKb: accumulator.sizeKb + (repository.size ?? 0),
}),
{ openIssues: 0, openPulls: 0, stars: 0, forks: 0, sizeKb: 0 },
);
return {
configured: true,
url: env.gitea.url,
organization: organization && {
name: organization.username ?? organization.name,
fullName: organization.full_name,
description: organization.description,
website: organization.website,
location: organization.location,
avatar: organization.avatar_url,
visibility: organization.visibility,
},
repositoryCount: repositories.length,
...totals,
repositories: repositories
.slice()
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
.slice(0, 6)
.map((repository) => ({
fullName: repository.full_name,
description: repository.description,
private: repository.private,
archived: repository.archived,
stars: repository.stars_count,
openIssues: repository.open_issues_count,
openPulls: repository.open_pr_counter,
updatedAt: repository.updated_at,
htmlUrl: repository.html_url,
})),
};
}
function recentEvents(limit = 15) {
return getDatabase()
.prepare('SELECT id, type, actor_id, payload, created_at FROM event_logs ORDER BY id DESC LIMIT ?')
.all(limit)
.map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null }));
}
export function registerOverviewRoutes(router) {
router.get(
'/api/overview',
async ({ context }) => {
const id = guildId();
const gitea = await giteaSnapshot();
return {
bot: botSnapshot(context.client, context.startedAt),
gitea,
database: databaseSnapshot(),
activity: {
openTickets: id ? countOpenTickets(id) : 0,
polls: id ? countPolls(id) : 0,
voiceChannels: id ? countVoiceChannels(id) : 0,
moderation: id ? countByAction(id) : [],
deployments: id ? countByStatus(id) : [],
environments: id ? lastDeploymentPerEnvironment(id) : [],
},
events: recentEvents(),
features: {
webhooks: env.webhook.enabled,
commandDeploys: env.web.allowCommandDeploys,
restart: env.web.allowRestart,
gitea: isGiteaConfigured(),
},
links: env.links,
};
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+260
View File
@@ -0,0 +1,260 @@
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { repos } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { notify } from '../../services/notifications/notification-service.js';
import { badRequest } from '../http.js';
import { runAutoDeployments } from '../services/deploy-service.js';
/** Release management, the publishing half of the SaaS pipeline (M16-T08). */
const log = createLogger('web:releases');
const NAME = /^[\w.-]{1,100}$/;
function target(params) {
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).');
const { owner, repo } = params;
if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.');
return { owner, repo, fullName: `${owner}/${repo}` };
}
const summarize = (release) => ({
id: release.id,
tag: release.tag_name,
name: release.name,
body: release.body,
draft: release.draft,
prerelease: release.prerelease,
target: release.target_commitish,
author: release.author?.login,
createdAt: release.created_at,
publishedAt: release.published_at,
htmlUrl: release.html_url,
assets: (release.assets ?? []).map((asset) => ({
id: asset.id,
name: asset.name,
size: asset.size,
downloads: asset.download_count,
url: asset.browser_download_url,
})),
});
/** Same grouping as `scripts/generate-changelog.js`, applied to Gitea commits. */
const SECTIONS = [
{ title: 'Nouveautés', test: (type) => type === 'feat' },
{ title: 'Corrections', test: (type) => type === 'fix' },
{ title: 'Performance', test: (type) => type === 'perf' },
{ title: 'Autres changements', test: (type) => !['feat', 'fix', 'perf'].includes(type) },
];
const CONVENTIONAL = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/;
/**
* Builds release notes from the commits that follow the previous tag.
* Commits that do not follow Conventional Commits are kept verbatim, so nothing
* silently disappears from the notes.
*/
export function buildReleaseNotes(commits, { previousTag = null } = {}) {
const parsed = commits.map((commit) => {
const subject = (commit.commit?.message ?? '').split('\n')[0].trim();
const match = CONVENTIONAL.exec(subject);
return {
subject,
sha: commit.sha?.slice(0, 8),
type: match?.groups.type ?? 'other',
scope: match?.groups.scope ?? null,
description: match?.groups.description ?? subject,
breaking: Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(commit.commit?.message ?? ''),
};
});
const lines = [];
const breaking = parsed.filter((commit) => commit.breaking);
if (breaking.length > 0) {
lines.push('### ⚠ Changements incompatibles', '');
for (const commit of breaking) lines.push(`- ${commit.description} (${commit.sha})`);
lines.push('');
}
for (const section of SECTIONS) {
const entries = parsed.filter((commit) => section.test(commit.type));
if (entries.length === 0) continue;
lines.push(`### ${section.title}`, '');
for (const commit of entries) {
const scope = commit.scope ? `**${commit.scope}** : ` : '';
lines.push(`- ${scope}${commit.description} (${commit.sha})`);
}
lines.push('');
}
if (previousTag) lines.push(`_Changements depuis \`${previousTag}\`._`);
return lines.join('\n').trim() || '_Aucun changement détecté._';
}
export function registerReleaseRoutes(router) {
router.get(
'/api/repositories/:owner/:repo/releases',
async ({ params, query }) => {
const { owner, repo } = target(params);
const list = await repos.listReleases(owner, repo, {
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50),
});
return { releases: list.map(summarize) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/repositories/:owner/:repo/tags',
async ({ params }) => {
const { owner, repo } = target(params);
const tags = await repos.listTags(owner, repo, { limit: 50 }).catch(() => []);
return {
tags: tags.map((tag) => ({
name: tag.name,
sha: tag.commit?.sha?.slice(0, 8),
url: tag.zipball_url,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
/** Proposes release notes before the release is actually created. */
router.post(
'/api/repositories/:owner/:repo/releases/notes',
async ({ params, body }) => {
const { owner, repo } = target(params);
const branch = String(body.target ?? '') || undefined;
const [commits, releases] = await Promise.all([
repos.listCommits(owner, repo, { sha: branch, limit: 50 }),
repos.listReleases(owner, repo, { limit: 1 }).catch(() => []),
]);
const previous = releases[0] ?? null;
// Gitea has no "compare since tag" endpoint on every version, so the cut is
// made on the published date of the previous release.
const since = previous?.published_at ? new Date(previous.published_at) : null;
const selected = since
? commits.filter((commit) => new Date(commit.commit?.author?.date ?? 0) > since)
: commits;
return {
previousTag: previous?.tag_name ?? null,
commitCount: selected.length,
notes: buildReleaseNotes(selected, { previousTag: previous?.tag_name ?? null }),
};
},
{ access: ACCESS_LEVELS.DEV },
);
router.post(
'/api/repositories/:owner/:repo/releases',
async ({ params, body, actor, context }) => {
const { owner, repo, fullName } = target(params);
const tagName = String(body.tag ?? '').trim();
if (!/^[\w.\-+/]{1,64}$/.test(tagName)) throw badRequest('Nom de tag invalide.');
const release = await repos.createRelease(owner, repo, {
tagName,
target: body.target ? String(body.target) : undefined,
name: String(body.name ?? tagName),
body: String(body.body ?? ''),
draft: Boolean(body.draft),
prerelease: Boolean(body.prerelease),
});
logEvent({
guildId: env.discord.guildId || null,
type: 'web.release.create',
actorId: actor.userId,
payload: { repository: fullName, tag: tagName, draft: Boolean(body.draft) },
});
// A draft is not public yet: no announcement, no deployment.
let deployments = [];
if (!release.draft) {
await announceRelease(context.client, fullName, release).catch((error) =>
log.warn('Could not announce the release', error),
);
if (body.deploy !== false) {
deployments = await runAutoDeployments(context.client, {
repository: fullName,
releaseTag: release.tag_name,
ref: release.target_commitish,
triggeredBy: actor.userId,
});
}
}
return { release: summarize(release), deployments };
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/repositories/:owner/:repo/releases/:id',
async ({ params, body, actor, context }) => {
const { owner, repo, fullName } = target(params);
const id = Number.parseInt(params.id, 10);
const before = await repos.getRelease(owner, repo, id);
const payload = {};
if ('name' in body) payload.name = String(body.name);
if ('body' in body) payload.body = String(body.body);
if ('draft' in body) payload.draft = Boolean(body.draft);
if ('prerelease' in body) payload.prerelease = Boolean(body.prerelease);
if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.');
const release = await repos.updateRelease(owner, repo, id, payload);
logEvent({
guildId: env.discord.guildId || null,
type: 'web.release.update',
actorId: actor.userId,
payload: { repository: fullName, tag: release.tag_name },
});
// Publishing a draft is the moment the release becomes real.
if (before.draft && !release.draft) {
await announceRelease(context.client, fullName, release).catch(() => null);
}
return summarize(release);
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/repositories/:owner/:repo/releases/:id',
async ({ params, actor }) => {
const { owner, repo, fullName } = target(params);
await repos.removeRelease(owner, repo, Number.parseInt(params.id, 10));
logEvent({
guildId: env.discord.guildId || null,
type: 'web.release.delete',
actorId: actor.userId,
payload: { repository: fullName, id: params.id },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
}
function announceRelease(client, fullName, release) {
if (!client) return Promise.resolve(null);
return notify(client, 'release', {
embeds: [
{
title: `${release.name || release.tag_name} — ${fullName}`,
url: release.html_url,
color: release.prerelease ? COLORS.warning : COLORS.gitea,
description: String(release.body ?? '').slice(0, 1800) || 'Nouvelle version publiée.',
footer: { text: release.prerelease ? 'Préversion' : 'Version stable' },
timestamp: release.published_at ?? new Date().toISOString(),
},
],
});
}
+541
View File
@@ -0,0 +1,541 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { org, repos } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { badRequest } from '../http.js';
/** Per-repository management (M16-T04). */
const NAME = /^[\w.-]{1,100}$/;
function target(params) {
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).');
const { owner, repo } = params;
if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.');
return { owner, repo, fullName: `${owner}/${repo}` };
}
const number = (value, field) => {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed) || parsed < 0) throw badRequest(`Valeur numérique attendue pour ${field}.`);
return parsed;
};
const audit = (actor, type, payload) =>
logEvent({ guildId: env.discord.guildId || null, type, actorId: actor.userId, payload });
const summarizeIssue = (issue) => ({
number: issue.number,
title: issue.title,
state: issue.state,
body: issue.body,
labels: (issue.labels ?? []).map((label) => ({ name: label.name, color: label.color })),
assignees: (issue.assignees ?? []).map((user) => user.login),
author: issue.user?.login,
authorAvatar: issue.user?.avatar_url,
comments: issue.comments,
createdAt: issue.created_at,
updatedAt: issue.updated_at,
closedAt: issue.closed_at,
milestone: issue.milestone?.title ?? null,
htmlUrl: issue.html_url,
});
const summarizePull = (pull) => ({
...summarizeIssue(pull),
draft: pull.draft,
mergeable: pull.mergeable,
merged: pull.merged,
mergedAt: pull.merged_at,
head: pull.head?.ref,
base: pull.base?.ref,
additions: pull.additions,
deletions: pull.deletions,
changedFiles: pull.changed_files,
});
export function registerRepositoryRoutes(router) {
router.get(
'/api/repositories',
async () => {
if (!isGiteaConfigured()) return { configured: false, repositories: [] };
const list = await org.listRepos({ limit: 100 });
return {
configured: true,
repositories: list.map((repository) => ({
fullName: repository.full_name,
name: repository.name,
owner: repository.owner?.login,
description: repository.description,
private: repository.private,
archived: repository.archived,
defaultBranch: repository.default_branch,
language: repository.language,
stars: repository.stars_count,
forks: repository.forks_count,
openIssues: repository.open_issues_count,
openPulls: repository.open_pr_counter,
releases: repository.release_counter,
sizeKb: repository.size,
updatedAt: repository.updated_at,
htmlUrl: repository.html_url,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/repositories/:owner/:repo',
async ({ params }) => {
const { owner, repo } = target(params);
const [details, branches, languages, topics, collaborators, release] = await Promise.all([
repos.get(owner, repo),
repos.listBranches(owner, repo, { limit: 100 }).catch(() => []),
repos.languages(owner, repo).catch(() => ({})),
repos.listTopics(owner, repo).catch(() => ({ topics: [] })),
repos.listCollaborators(owner, repo).catch(() => []),
repos.latestRelease(owner, repo).catch(() => null),
]);
return {
fullName: details.full_name,
name: details.name,
owner: details.owner?.login,
description: details.description,
website: details.website,
private: details.private,
archived: details.archived,
template: details.template,
fork: details.fork,
mirror: details.mirror,
empty: details.empty,
defaultBranch: details.default_branch,
defaultMergeStyle: details.default_merge_style,
allowMergeCommits: details.allow_merge_commits,
allowRebase: details.allow_rebase,
allowSquash: details.allow_squash_merge,
hasIssues: details.has_issues,
hasPullRequests: details.has_pull_requests,
hasWiki: details.has_wiki,
hasActions: details.has_actions,
hasReleases: details.has_releases,
stars: details.stars_count,
forks: details.forks_count,
watchers: details.watchers_count,
openIssues: details.open_issues_count,
openPulls: details.open_pr_counter,
releases: details.release_counter,
sizeKb: details.size,
createdAt: details.created_at,
updatedAt: details.updated_at,
htmlUrl: details.html_url,
cloneUrl: details.clone_url,
sshUrl: details.ssh_url,
permissions: details.permissions,
languages,
topics: topics.topics ?? [],
branches: branches.map((branch) => ({
name: branch.name,
protected: branch.protected,
commit: branch.commit?.id?.slice(0, 8),
commitMessage: branch.commit?.message?.split('\n')[0],
commitAt: branch.commit?.timestamp,
})),
collaborators: collaborators.map((user) => ({
login: user.login,
fullName: user.full_name,
avatar: user.avatar_url,
permissions: user.permissions,
})),
latestRelease: release && {
tag: release.tag_name,
name: release.name,
publishedAt: release.published_at,
htmlUrl: release.html_url,
},
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/repositories/:owner/:repo',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const allowed = [
'description',
'website',
'private',
'archived',
'default_branch',
'default_merge_style',
'has_issues',
'has_pull_requests',
'has_wiki',
'has_actions',
'has_releases',
'allow_merge_commits',
'allow_rebase',
'allow_squash_merge',
];
const payload = Object.fromEntries(Object.entries(body).filter(([key]) => allowed.includes(key)));
if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.');
await repos.update(owner, repo, payload);
audit(actor, 'web.repository.update', { repository: fullName, fields: Object.keys(payload) });
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
/** Deleting a repository is irreversible, so the full name must be typed back. */
router.delete(
'/api/repositories/:owner/:repo',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
if (body.confirm !== fullName) {
throw badRequest(`Pour confirmer la suppression, renvoie exactement « ${fullName} ».`);
}
await repos.remove(owner, repo);
audit(actor, 'web.repository.delete', { repository: fullName });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.get(
'/api/repositories/:owner/:repo/topics',
async ({ params }) => {
const { owner, repo } = target(params);
return repos.listTopics(owner, repo);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.put(
'/api/repositories/:owner/:repo/topics',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const topics = Array.isArray(body.topics) ? body.topics.map((topic) => String(topic).trim()) : null;
if (!topics) throw badRequest('`topics` doit être une liste.');
await repos.replaceTopics(owner, repo, topics);
audit(actor, 'web.repository.topics', { repository: fullName, topics });
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
// --- Issues ----------------------------------------------------------------
router.get(
'/api/repositories/:owner/:repo/issues',
async ({ params, query }) => {
const { owner, repo } = target(params);
const list = await repos.listIssues(owner, repo, {
state: query.get('state') ?? 'open',
page: Number.parseInt(query.get('page') ?? '1', 10),
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50),
q: query.get('q') ?? undefined,
});
return { issues: list.map(summarizeIssue) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/repositories/:owner/:repo/issues',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const title = String(body.title ?? '').trim();
if (title.length < 3) throw badRequest('Le titre doit faire au moins 3 caractères.');
const issue = await repos.createIssue(owner, repo, {
title,
body: String(body.body ?? ''),
labels: body.labels ?? undefined,
assignees: body.assignees ?? undefined,
});
audit(actor, 'web.issue.create', { repository: fullName, number: issue.number });
return summarizeIssue(issue);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/repositories/:owner/:repo/issues/:number',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const issueNumber = number(params.number, 'number');
const payload = {};
if ('state' in body) {
if (!['open', 'closed'].includes(body.state)) throw badRequest('État attendu : open ou closed.');
payload.state = body.state;
}
for (const field of ['title', 'body', 'assignees', 'labels', 'milestone']) {
if (field in body) payload[field] = body[field];
}
if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.');
const issue = await repos.updateIssue(owner, repo, issueNumber, payload);
audit(actor, 'web.issue.update', {
repository: fullName,
number: issueNumber,
fields: Object.keys(payload),
});
return summarizeIssue(issue);
},
{ access: ACCESS_LEVELS.DEV },
);
router.post(
'/api/repositories/:owner/:repo/issues/:number/comments',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const issueNumber = number(params.number, 'number');
const message = String(body.body ?? '').trim();
if (message === '') throw badRequest('Le commentaire est vide.');
const comment = await repos.commentIssue(owner, repo, issueNumber, message);
audit(actor, 'web.issue.comment', { repository: fullName, number: issueNumber });
return { id: comment.id, htmlUrl: comment.html_url };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/repositories/:owner/:repo/labels',
async ({ params }) => {
const { owner, repo } = target(params);
return { labels: await repos.listLabels(owner, repo) };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Pull requests ---------------------------------------------------------
router.get(
'/api/repositories/:owner/:repo/pulls',
async ({ params, query }) => {
const { owner, repo } = target(params);
const list = await repos.listPulls(owner, repo, {
state: query.get('state') ?? 'open',
page: Number.parseInt(query.get('page') ?? '1', 10),
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50),
});
return { pulls: list.map(summarizePull) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/repositories/:owner/:repo/pulls',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const { title, head, base } = body;
if (!title || !head || !base) throw badRequest('`title`, `head` et `base` sont obligatoires.');
const pull = await repos.createPull(owner, repo, {
title: String(title),
body: String(body.body ?? ''),
head: String(head),
base: String(base),
});
audit(actor, 'web.pull.create', { repository: fullName, number: pull.number });
return summarizePull(pull);
},
{ access: ACCESS_LEVELS.DEV },
);
router.post(
'/api/repositories/:owner/:repo/pulls/:number/merge',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const pullNumber = number(params.number, 'number');
const style = String(body.style ?? 'squash');
if (!['merge', 'rebase', 'rebase-merge', 'squash'].includes(style)) {
throw badRequest('Méthode de merge inconnue.');
}
await repos.mergePull(owner, repo, pullNumber, {
style,
title: body.title ? String(body.title) : undefined,
message: body.message ? String(body.message) : undefined,
deleteBranch: Boolean(body.deleteBranch),
});
audit(actor, 'web.pull.merge', { repository: fullName, number: pullNumber, style });
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
// --- Branches and commits --------------------------------------------------
router.get(
'/api/repositories/:owner/:repo/commits',
async ({ params, query }) => {
const { owner, repo } = target(params);
const list = await repos.listCommits(owner, repo, {
sha: query.get('branch') ?? undefined,
page: Number.parseInt(query.get('page') ?? '1', 10),
limit: Math.min(Number.parseInt(query.get('limit') ?? '25', 10), 50),
});
return {
commits: list.map((commit) => ({
sha: commit.sha,
shortSha: commit.sha?.slice(0, 8),
message: commit.commit?.message?.split('\n')[0],
author: commit.commit?.author?.name,
authorLogin: commit.author?.login,
avatar: commit.author?.avatar_url,
date: commit.commit?.author?.date,
htmlUrl: commit.html_url,
stats: commit.stats,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/repositories/:owner/:repo/branches',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const newBranchName = String(body.name ?? '').trim();
if (newBranchName === '') throw badRequest('Nom de branche manquant.');
const branch = await repos.createBranch(owner, repo, {
newBranchName,
oldBranchName: body.from ? String(body.from) : undefined,
});
audit(actor, 'web.branch.create', { repository: fullName, branch: newBranchName });
return { name: branch.name };
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/repositories/:owner/:repo/branches',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const branch = String(body.name ?? '').trim();
if (branch === '') throw badRequest('Nom de branche manquant.');
await repos.removeBranch(owner, repo, branch);
audit(actor, 'web.branch.delete', { repository: fullName, branch });
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
// --- Collaborators ---------------------------------------------------------
router.put(
'/api/repositories/:owner/:repo/collaborators/:username',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const permission = String(body.permission ?? 'write');
if (!['read', 'write', 'admin'].includes(permission)) throw badRequest('Permission inconnue.');
await repos.addCollaborator(owner, repo, params.username, permission);
audit(actor, 'web.collaborator.add', { repository: fullName, user: params.username, permission });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.delete(
'/api/repositories/:owner/:repo/collaborators/:username',
async ({ params, actor }) => {
const { owner, repo, fullName } = target(params);
await repos.removeCollaborator(owner, repo, params.username);
audit(actor, 'web.collaborator.remove', { repository: fullName, user: params.username });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
// --- Webhooks and actions --------------------------------------------------
router.get(
'/api/repositories/:owner/:repo/hooks',
async ({ params }) => {
const { owner, repo } = target(params);
const hooks = await repos.listHooks(owner, repo).catch(() => []);
return {
hooks: hooks.map((hook) => ({
id: hook.id,
type: hook.type,
active: hook.active,
events: hook.events,
url: hook.config?.url,
createdAt: hook.created_at,
})),
};
},
{ access: ACCESS_LEVELS.DEV },
);
/**
* Convenience route: wires Gitea to this bot's own webhook endpoint with the
* secret already configured, which is the step people most often get wrong.
*/
router.post(
'/api/repositories/:owner/:repo/hooks',
async ({ params, body, actor }) => {
const { owner, repo, fullName } = target(params);
const url = String(body.url ?? '').trim() || `${env.web.publicUrl}${env.webhook.path}`;
if (!url.startsWith('http')) throw badRequest('URL de webhook invalide.');
const secret = String(body.secret ?? '') || env.webhook.secret;
if (!secret) throw badRequest('Aucun secret disponible : renseigne `GITEA_WEBHOOK_SECRET`.');
const hook = await repos.createHook(owner, repo, {
url,
secret,
events: body.events ?? ['issues', 'pull_request', 'push', 'release'],
});
audit(actor, 'web.hook.create', { repository: fullName, url });
return { id: hook.id, url };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.delete(
'/api/repositories/:owner/:repo/hooks/:id',
async ({ params, actor }) => {
const { owner, repo, fullName } = target(params);
await repos.removeHook(owner, repo, number(params.id, 'id'));
audit(actor, 'web.hook.delete', { repository: fullName, hook: params.id });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.get(
'/api/repositories/:owner/:repo/actions',
async ({ params }) => {
const { owner, repo } = target(params);
// Gitea Actions is absent before 1.20 and returns 404 when disabled on the repo.
const payload = await repos.listActionTasks(owner, repo, { limit: 20 }).catch(() => null);
if (!payload) return { available: false, tasks: [] };
const tasks = Array.isArray(payload) ? payload : (payload.workflow_runs ?? payload.data ?? []);
return {
available: true,
tasks: tasks.map((task) => ({
id: task.id,
name: task.name,
headBranch: task.head_branch,
headSha: task.head_sha?.slice(0, 8),
status: task.status,
conclusion: task.conclusion,
event: task.event,
runNumber: task.run_number,
createdAt: task.created_at,
updatedAt: task.updated_at,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+366
View File
@@ -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 },
);
}