Author SHA1 Message Date
nocodeandClaude Opus 5 27b5ea251c docs(web): document the wiki, the settings and the command publishing
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:19 +02:00
nocodeandClaude Opus 5 553c69dafe feat(wiki): add the reading site and its editor
The renderer escapes HTML before any transformation and drops
`javascript:` links. Pages are written by the team, but a renderer that
relies on that is one mistake away from being a hole.

The editor previews as you type: legal pages are long, and writing Markdown
blind is how broken tables end up published.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:19 +02:00
nocodeandClaude Opus 5 faa296937d feat(wiki): serve a public documentation written from the panel
Pages live in SQLite and are read without a session: documentation nobody
can reach without an account is not documentation. Drafts answer 404 even
when their address is guessed, and the site never falls back to the
dashboard shell, which would send a visitor to a login screen.

The wiki ships with terms of use and a privacy policy written against the
revised Swiss LPD, describing table by table what this codebase actually
stores. Both are marked protected: they can be rewritten, not deleted, and
a deleted one comes back on the next start — a bot that processes personal
data must always be able to show its notice.

The bracketed details still have to be completed and the whole reviewed;
this is a starting point written from the schema, not legal advice.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:19 +02:00
nocodeandClaude Opus 5 22e235e76a style(web): adopt the official FWS mark and its palette
The placeholder mark was an Arch-blue chevron. The site now carries the FWS
logo — cyan ring on dark navy — and its accent colour follows, so the
dashboard and the brand no longer disagree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:19 +02:00
nocodeandClaude Opus 5 d7ab575550 fix(web): make the whole repository card open the repository
Only the name was a link, so most of a rectangle that reacts to the pointer
led nowhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:18 +02:00
nocodeandClaude Opus 5 7595dcb95a feat(web): publish the slash commands from the panel
Registering the commands was the one routine step that still needed shell
access on the host, which is awkward when the bot runs behind a hosting
panel. Guild commands take effect immediately, so the button says what it
did as soon as it returns.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:18 +02:00
nocodeandClaude Opus 5 8384d1b510 feat(voice): take back the generated channels the database forgot
A voice channel outlives the process that made it. A restored backup, a
wiped `data/` folder or a redeployment shipping a fresh database all leave
real channels behind that nothing manages any more: they are never cleaned
up, and their owner can no longer rename or lock them.

At startup the bot now reclaims the channels sitting in a trigger's own
category and named after its template — a channel created by hand is never
touched. Those still in use go back to whoever is inside; the empty ones are
leftovers and are removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:18 +02:00
nocodeandClaude Opus 5 7d568e416d feat(settings): make the server settings real, and widen them
The dashboard offered seven switches that nothing read: they promised a
behaviour the bot did not have, which is worse than offering nothing.

Every setting is now declared once, with its type, its bounds and its
explanation, and the services read it: the welcome message and its wording,
the automatic role, departure notices, the private notice sent to a
sanctioned member, the default mute duration, how much history a ban erases,
whether a closed ticket is deleted or archived, and an optional role mention
on the Gitea notifications.

A test walks the sources and fails when a declared key is read nowhere, so
the list cannot drift back into decoration.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 21:48:18 +02:00
37 changed files with 2488 additions and 180 deletions

No files matched your search

+4
View File
@@ -322,6 +322,10 @@ The bot serves its own admin site: Gitea organization, repositories, releases, d
No added dependency: `node:http` for the server, `node:sqlite` for the sessions, and a plain JavaScript front-end served as is. No added dependency: `node:http` for the server, `node:sqlite` for the sessions, and a plain JavaScript front-end served as is.
The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed.
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, tickets, voice, notifications.
### 6.1 Getting started ### 6.1 Getting started
Without a `.env` the bot refuses to start, so the configuration wizard runs on its own, without connecting to Discord. Without a `.env` the bot refuses to start, so the configuration wizard runs on its own, without connecting to Discord.
+4
View File
@@ -324,6 +324,10 @@ Le bot sert son propre site d'administration : organisation Gitea, dépôts, rel
Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour les sessions, et un front en JavaScript natif servi tel quel. Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour les sessions, et un front en JavaScript natif servi tel quel.
Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire.
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, tickets, vocaux, notifications.
### 6.1 Démarrer ### 6.1 Démarrer
Sans `.env`, le bot refuse de démarrer : l'assistant de configuration se lance donc seul, sans connexion à Discord. Sans `.env`, le bot refuse de démarrer : l'assistant de configuration se lance donc seul, sans connexion à Discord.
+3 -1
View File
@@ -19,6 +19,7 @@ fws-discordbot/
│ ├── index.js # Point d'entrée │ ├── index.js # Point d'entrée
│ ├── config/ │ ├── config/
│ │ ├── env.js # Lecture et validation des variables d'environnement │ │ ├── env.js # Lecture et validation des variables d'environnement
│ │ ├── guild-settings.js # Réglages modifiables depuis le panel, et leur schéma
│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets │ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets
│ ├── core/ │ ├── core/
│ │ ├── client.js # Client Discord et intents │ │ ├── client.js # Client Discord et intents
@@ -41,7 +42,8 @@ fws-discordbot/
│ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès │ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès
│ │ ├── api/ # Un module par domaine exposé │ │ ├── api/ # Un module par domaine exposé
│ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements │ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements
│ │ └── public/ # Front JavaScript natif, servi tel quel │ │ ├── public/ # Front JavaScript natif, servi tel quel
│ │ └── public/wiki.* # Site de documentation public, servi sans session
│ ├── ui/ # Embeds et boutons standardisés │ ├── ui/ # Embeds et boutons standardisés
│ └── utils/ # Retry, cooldown… │ └── utils/ # Retry, cooldown…
└── tests/ # Tests node:test └── tests/ # Tests node:test
+33 -4
View File
@@ -142,7 +142,36 @@ Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — u
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte. Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
## 7. Jetons d'API ## 7. Wiki public
Le bot sert une documentation publique sur **`/wiki`**, lisible sans compte, écrite depuis **Tableau de bord → Wiki**.
- Les pages sont rédigées en Markdown, avec un aperçu en direct dans l'éditeur.
- Une page reste en **brouillon** tant qu'elle n'est pas publiée ; un brouillon renvoie 404 même si on devine son adresse.
- Les pages sont regroupées par **catégorie** et ordonnées par **position**.
- La recherche porte sur les titres, les résumés et le contenu des pages publiées.
Le rendu Markdown échappe le HTML **avant** toute transformation et refuse les liens `javascript:`. Les pages sont écrites par l'équipe, mais un moteur qui compte là-dessus est à une erreur près d'être une faille.
### Pages légales
Au premier démarrage, trois pages sont créées : un accueil et deux pages **protégées** — **Conditions d'utilisation** et **Politique de confidentialité**. Elles sont modifiables mais pas supprimables : un bot qui traite des données personnelles doit pouvoir montrer ses conditions.
La politique de confidentialité est rédigée selon la **LPD suisse révisée** (RS 235.1, en vigueur depuis le 1ᵉʳ septembre 2023) et décrit ce que ce code stocke réellement, table par table. Les mentions entre crochets — responsable du traitement, adresse, hébergeur — doivent être complétées, et l'ensemble relu par une personne compétente avant publication.
Une page supprimée par erreur est recréée au démarrage suivant ; une page réécrite ne l'est jamais.
## 8. Réglages du serveur
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
## 9. Publier les commandes slash
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
## 10. Jetons d'API
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée. Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
@@ -152,7 +181,7 @@ curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment. Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
## 8. Sécurité ## 11. Sécurité
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site. - **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`. - **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
@@ -163,7 +192,7 @@ Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personn
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact. - **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur. - **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
## 9. Fonctionnement interne ## 12. Fonctionnement interne
```text ```text
src/web/ src/web/
@@ -207,7 +236,7 @@ Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le co
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port. Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
## 10. Dépannage ## 13. Dépannage
| Symptôme | Cause probable | | Symptôme | Cause probable |
| ---------------------------------------------- | ------------------------------------------------------------------------------- | | ---------------------------------------------- | ------------------------------------------------------------------------------- |
+9 -6
View File
@@ -1,8 +1,10 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js';
import { import {
assertModerationTarget, assertModerationTarget,
logModerationAction, logModerationAction,
notifyTarget,
targetNoticeEmbed, targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
@@ -27,16 +29,17 @@ export const data = new SlashCommandBuilder()
export async function execute(interaction) { export async function execute(interaction) {
const user = interaction.options.getUser('user', true); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason'); const reason = interaction.options.getString('reason');
const deleteDays = interaction.options.getInteger('delete_days') ?? 0; // Falls back to what the server configured rather than to a blunt zero.
const deleteDays =
interaction.options.getInteger('delete_days') ??
Math.round(readSetting('moderation.banDeleteMessageHours', interaction.guildId) / 24);
const member = await interaction.guild.members.fetch(user.id).catch(() => null); const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) { if (member) {
assertModerationTarget(interaction, member); assertModerationTarget(interaction, member);
await member await notifyTarget(member, {
.send({ embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], });
})
.catch(() => {});
} }
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
+4 -5
View File
@@ -4,6 +4,7 @@ import {
assertModerationTarget, assertModerationTarget,
fetchTargetMember, fetchTargetMember,
logModerationAction, logModerationAction,
notifyTarget,
targetNoticeEmbed, targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
@@ -26,11 +27,9 @@ export async function execute(interaction) {
assertModerationTarget(interaction, target); assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target await notifyTarget(target, {
.send({ embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], });
})
.catch(() => {});
await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`); await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
+8 -7
View File
@@ -1,10 +1,12 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js';
import { import {
assertModerationTarget, assertModerationTarget,
fetchTargetMember, fetchTargetMember,
formatDuration, formatDuration,
logModerationAction, logModerationAction,
notifyTarget,
targetNoticeEmbed, targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
@@ -20,7 +22,6 @@ export const data = new SlashCommandBuilder()
option option
.setName('minutes') .setName('minutes')
.setDescription('Durée de la sanction, en minutes') .setDescription('Durée de la sanction, en minutes')
.setRequired(true)
.setMinValue(1) .setMinValue(1)
.setMaxValue(40_320), .setMaxValue(40_320),
) )
@@ -29,7 +30,9 @@ export const data = new SlashCommandBuilder()
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */ /** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) { export async function execute(interaction) {
const user = interaction.options.getUser('user', true); const user = interaction.options.getUser('user', true);
const minutes = interaction.options.getInteger('minutes', true); const minutes =
interaction.options.getInteger('minutes') ??
readSetting('moderation.defaultMuteMinutes', interaction.guildId);
const reason = interaction.options.getString('reason'); const reason = interaction.options.getString('reason');
const durationMs = minutes * 60_000; const durationMs = minutes * 60_000;
@@ -45,11 +48,9 @@ export async function execute(interaction) {
reason, reason,
durationMs, durationMs,
}); });
await target await notifyTarget(target, {
.send({ embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], });
})
.catch(() => {});
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
+9 -10
View File
@@ -5,6 +5,7 @@ import {
assertModerationTarget, assertModerationTarget,
fetchTargetMember, fetchTargetMember,
logModerationAction, logModerationAction,
notifyTarget,
targetNoticeEmbed, targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
@@ -32,16 +33,14 @@ export async function execute(interaction) {
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason }); await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' }); const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await target await notifyTarget(target, {
.send({ embeds: [
embeds: [ targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ name: 'Avertissements',
name: 'Avertissements', value: String(total),
value: String(total), }),
}), ],
], });
})
.catch(() => {});
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
+250
View File
@@ -0,0 +1,250 @@
import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js';
import { env } from './env.js';
/**
* Settings a server can change without touching the `.env` (M16-T13).
*
* Single source of truth: the form, the validation and the values the services
* read all come from here. A setting that is not read by anything has no
* business being in this list — a switch that does nothing is worse than no
* switch at all.
*/
export const SETTING_SECTIONS = Object.freeze([
{
id: 'welcome',
title: 'Arrivées et départs',
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
},
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{
id: 'voice',
title: 'Salons vocaux',
summary: 'Salons temporaires créés par les déclencheurs.',
},
{ id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' },
{ id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' },
]);
export const GUILD_SETTINGS = Object.freeze([
// --- Arrivées et départs ---------------------------------------------------
{
key: 'welcome.enabled',
section: 'welcome',
label: 'Message de bienvenue',
help: 'Publier un message dans le salon d’accueil à chaque arrivée.',
type: 'bool',
default: true,
},
{
key: 'welcome.message',
section: 'welcome',
label: 'Texte de bienvenue',
help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.',
type: 'text',
default: 'Bienvenue sur le serveur **{server}** !',
maxLength: 500,
},
{
key: 'welcome.showRules',
section: 'welcome',
label: 'Rappeler le règlement',
help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.',
type: 'bool',
default: true,
},
{
key: 'welcome.directMessage',
section: 'welcome',
label: 'Message privé de bienvenue',
help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.',
type: 'bool',
default: false,
},
{
key: 'members.autoRole',
section: 'welcome',
label: 'Attribuer le rôle d’arrivée',
help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.',
type: 'bool',
default: true,
},
{
key: 'departure.announce',
section: 'welcome',
label: 'Annoncer les départs',
help: 'Publie une ligne dans les logs quand un membre quitte le serveur.',
type: 'bool',
default: true,
},
// --- Modération ------------------------------------------------------------
{
key: 'moderation.dmTarget',
section: 'moderation',
label: 'Prévenir le membre sanctionné',
help: 'Envoie un message privé expliquant la sanction et son motif.',
type: 'bool',
default: true,
},
{
key: 'moderation.defaultMuteMinutes',
section: 'moderation',
label: 'Durée d’exclusion par défaut (min)',
help: 'Proposée quand `/mute` est lancé sans durée.',
type: 'int',
default: 60,
min: 1,
max: 40_320,
},
{
key: 'moderation.banDeleteMessageHours',
section: 'moderation',
label: 'Messages supprimés au bannissement (h)',
help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.',
type: 'int',
default: 0,
min: 0,
max: 168,
advanced: true,
},
// --- Tickets ---------------------------------------------------------------
{
key: 'tickets.deleteChannelOnClose',
section: 'tickets',
label: 'Supprimer le salon à la clôture',
help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.',
type: 'bool',
default: true,
},
// --- Salons vocaux ---------------------------------------------------------
{
key: 'voice.adoptOrphans',
section: 'voice',
label: 'Récupérer les salons orphelins',
help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.',
type: 'bool',
default: true,
},
// --- Notifications ---------------------------------------------------------
{
key: 'notifications.mentionRoleId',
section: 'notifications',
label: 'Rôle à mentionner',
help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.',
type: 'snowflake',
default: '',
advanced: true,
},
// --- Tableau de bord -------------------------------------------------------
{
key: 'deploy.requireConfirmation',
section: 'interface',
label: 'Confirmation avant déploiement',
help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.',
type: 'bool',
default: true,
},
{
key: 'web.defaultMode',
section: 'interface',
label: 'Mode d’affichage par défaut',
help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.',
type: 'enum',
options: ['simple', 'advanced'],
default: 'simple',
},
]);
export const SETTING_BY_KEY = Object.freeze(
Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])),
);
/** Coerces a stored value to the declared type, falling back on the default. */
function coerce(setting, value) {
if (value === null || value === undefined) return setting.default;
switch (setting.type) {
case 'bool':
return Boolean(value);
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return setting.default;
if (setting.min !== undefined && parsed < setting.min) return setting.min;
if (setting.max !== undefined && parsed > setting.max) return setting.max;
return parsed;
}
case 'enum':
return setting.options.includes(value) ? value : setting.default;
default:
return String(value);
}
}
/**
* Reads a setting. Never throws: called from event handlers that must keep
* working even when the database is momentarily unavailable.
*/
export function readSetting(key, guildId = env.discord.guildId) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
return coerce(setting, resolveSetting(guildId, key, setting.default));
}
/** Validates then stores a setting. Returns the stored value. */
export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
const message = validateSetting(key, value);
if (message) throw new Error(message);
const stored = coerce(setting, value);
setSetting(guildId, key, stored, updatedBy);
return stored;
}
/** Returns null when the value is acceptable, a French message otherwise. */
export function validateSetting(key, value) {
const setting = SETTING_BY_KEY[key];
if (!setting) return `Réglage inconnu : ${key}`;
switch (setting.type) {
case 'bool':
return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.';
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.';
if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`;
if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`;
return null;
}
case 'enum':
return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`;
case 'snowflake': {
const text = String(value ?? '').trim();
return text === '' || /^\d{17,20}$/.test(text)
? null
: 'Un identifiant Discord est composé de 17 à 20 chiffres.';
}
default: {
const text = String(value ?? '');
if (setting.maxLength && text.length > setting.maxLength) {
return `${setting.maxLength} caractères maximum.`;
}
return null;
}
}
}
/** Every setting with its current value, for the settings page. */
export function allSettings(guildId = env.discord.guildId) {
return Object.fromEntries(
GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]),
);
}
+21
View File
@@ -0,0 +1,21 @@
-- Public wiki pages, written from the dashboard and served without a session (M17)
CREATE TABLE IF NOT EXISTS wiki_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
summary TEXT,
content TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'Général',
position INTEGER NOT NULL DEFAULT 0,
published INTEGER NOT NULL DEFAULT 0,
-- A legal page is protected from deletion: the bot must always be able to
-- point at its terms and its privacy notice.
protected INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_wiki_published ON wiki_pages (published, category, position);
@@ -0,0 +1,106 @@
import { getDatabase } from '../index.js';
/** Public wiki pages (M17). */
const parse = (row) =>
row ? { ...row, published: Boolean(row.published), protected: Boolean(row.protected) } : null;
export function createPage({
slug,
title,
summary = null,
content = '',
category = 'Général',
position = 0,
published = false,
isProtected = false,
createdBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO wiki_pages
(slug, title, summary, content, category, position, published, protected, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
slug,
title,
summary,
content,
category,
position,
published ? 1 : 0,
isProtected ? 1 : 0,
createdBy,
createdBy,
);
return getPage(Number(lastInsertRowid));
}
export function getPage(id) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE id = ?').get(id) ?? null);
}
export function getPageBySlug(slug) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE slug = ?').get(slug) ?? null);
}
/** Published pages only, in reading order — what the public site shows. */
export function listPublished() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages WHERE published = 1 ORDER BY category, position, title')
.all()
.map(parse);
}
export function listAllPages() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages ORDER BY category, position, title')
.all()
.map(parse);
}
const UPDATABLE = Object.freeze({
slug: (value) => value,
title: (value) => value,
summary: (value) => value,
content: (value) => value,
category: (value) => value,
position: (value) => Number.parseInt(value, 10) || 0,
published: (value) => (value ? 1 : 0),
});
export function updatePage(id, patch, updatedBy = null) {
const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE);
if (entries.length === 0) return getPage(id);
const assignments = entries.map(([key]) => `${key} = ?`).join(', ');
const values = entries.map(([key, value]) => UPDATABLE[key](value));
getDatabase()
.prepare(
`UPDATE wiki_pages SET ${assignments}, updated_by = ?, updated_at = datetime('now') WHERE id = ?`,
)
.run(...values, updatedBy, id);
return getPage(id);
}
export function removePage(id) {
return getDatabase().prepare('DELETE FROM wiki_pages WHERE id = ? AND protected = 0').run(id).changes;
}
export function countPages() {
return getDatabase().prepare('SELECT COUNT(*) AS count FROM wiki_pages').get().count;
}
/** Full-text-ish search over the published pages, good enough for a small wiki. */
export function searchPublished(term) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT * FROM wiki_pages
WHERE published = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)
ORDER BY category, position, title LIMIT 25`,
)
.all(needle, needle, needle)
.map(parse);
}
+10 -1
View File
@@ -2,7 +2,11 @@ import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js'; import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js'; import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js'; import {
adoptOrphanVoiceChannels,
startVoiceJanitor,
sweepVoiceChannels,
} from '../services/voice/voice-service.js';
const log = createLogger('discord'); const log = createLogger('discord');
@@ -11,6 +15,11 @@ export const once = true;
export async function execute(client) { export async function execute(client) {
startPollScheduler(client); startPollScheduler(client);
// Channels outlive the process: take back the ones the database forgot before
// the sweep decides they are not ours.
await adoptOrphanVoiceChannels(client).catch((error) =>
log.warn('Could not recover the orphan voice channels', error),
);
await sweepVoiceChannels(client); await sweepVoiceChannels(client);
startVoiceJanitor(client); startVoiceJanitor(client);
startBotStatusRotation(client); startBotStatusRotation(client);
+2 -1
View File
@@ -1,4 +1,5 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { readSetting } from '../config/guild-settings.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { import {
assignMemberRole, assignMemberRole,
@@ -16,5 +17,5 @@ export async function execute(client, member) {
await assignMemberRole(member); await assignMemberRole(member);
await sendWelcome(client, member); await sendWelcome(client, member);
await sendWelcomeDirectMessage(member); if (readSetting('welcome.directMessage', member.guild.id)) await sendWelcomeDirectMessage(member);
} }
+15 -2
View File
@@ -1,5 +1,6 @@
import { COLORS } from '../../config/constants.js'; import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { baseEmbed } from '../../ui/embeds.js'; import { baseEmbed } from '../../ui/embeds.js';
@@ -14,6 +15,10 @@ async function sendTo(channel) {
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */ /** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) { export async function sendWelcome(client, member) {
if (!readSetting('welcome.enabled', member.guild.id)) {
log.debug('Welcome message disabled for this guild');
return;
}
if (!env.channels.welcome) { if (!env.channels.welcome) {
log.debug('No welcome channel configured'); log.debug('No welcome channel configured');
return; return;
@@ -25,13 +30,17 @@ export async function sendWelcome(client, member) {
return; return;
} }
const greeting =
readSetting('welcome.message', member.guild.id).replaceAll('{server}', member.guild.name) ||
DEFAULT_WELCOME;
const embed = baseEmbed(COLORS.primary) const embed = baseEmbed(COLORS.primary)
.setTitle('🎉 Nouveau membre') .setTitle('🎉 Nouveau membre')
.setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`) .setDescription(`${member} vient d’arriver. ${greeting}`)
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true }) .addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 })); .setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (env.channels.rules) { if (env.channels.rules && readSetting('welcome.showRules', member.guild.id)) {
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` }); embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
} }
@@ -41,6 +50,8 @@ export async function sendWelcome(client, member) {
/** Gives the default member role (M7-T03). */ /** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) { export async function assignMemberRole(member) {
if (!readSetting('members.autoRole', member.guild.id)) return;
const roleId = env.roles.member; const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return; if (!roleId || member.roles.cache.has(roleId)) return;
@@ -82,6 +93,8 @@ export async function sendWelcomeDirectMessage(member) {
/** Logs a departure in the log channel (M7-T04). */ /** Logs a departure in the log channel (M7-T04). */
export async function announceDeparture(client, member) { export async function announceDeparture(client, member) {
if (!readSetting('departure.announce', member.guild.id)) return;
const channelId = env.channels.logs || env.channels.modLogs; const channelId = env.channels.logs || env.channels.modLogs;
if (!channelId) return; if (!channelId) return;
@@ -1,5 +1,6 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js'; import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
@@ -95,6 +96,19 @@ export async function sendModerationLog(
await channel.send({ embeds: [embed] }).catch(() => {}); await channel.send({ embeds: [embed] }).catch(() => {});
} }
/**
* Sends the private notice to the sanctioned member, when the server wants one
* (M8-T07). Never throws: plenty of accounts refuse direct messages, and that
* must not turn a successful sanction into an error.
*/
export async function notifyTarget(member, payload) {
if (!readSetting('moderation.dmTarget', member.guild.id)) return false;
return member
.send(payload)
.then(() => true)
.catch(() => false);
}
/** Direct message sent to the member who is being moderated (M8-T07). */ /** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action]; const meta = MODERATION_ACTIONS[action];
@@ -1,4 +1,5 @@
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js'; import { errorEmbed } from '../../ui/embeds.js';
@@ -58,7 +59,15 @@ export async function notify(client, type, payload) {
log.warn(`Notification channel unavailable for ${type}`, { channelId }); log.warn(`Notification channel unavailable for ${type}`, { channelId });
return null; return null;
} }
return channel.send(payload);
// An optional ping, prepended rather than replacing whatever content the
// caller already prepared.
const mention = readSetting('notifications.mentionRoleId');
const message = mention
? { ...payload, content: payload.content ? `<@&${mention}> ${payload.content}` : `<@&${mention}>` }
: payload;
return channel.send(message);
} }
/** Reports an unexpected failure in the technical channel (M9-T07). */ /** Reports an unexpected failure in the technical channel (M9-T07). */
+14 -2
View File
@@ -1,5 +1,6 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js'; import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { readSetting } from '../../config/guild-settings.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
@@ -235,10 +236,13 @@ export async function closeTicket(interaction, reason = null) {
payload: { ticketId: ticket.id, reason }, payload: { ticketId: ticket.id, reason },
}); });
const deleteChannel = readSetting('tickets.deleteChannelOnClose', ticket.guild_id);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
successEmbed( successEmbed(
`Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`, deleteChannel
? `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`
: `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon reste consultable, mais plus personne ne peut y écrire.`,
), ),
], ],
}); });
@@ -255,7 +259,15 @@ export async function closeTicket(interaction, reason = null) {
); );
const channel = interaction.channel; const channel = interaction.channel;
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); if (deleteChannel) {
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
return;
}
// Archived instead of deleted: the author keeps read access, nobody can write.
await channel?.permissionOverwrites
.edit(ticket.author_id, { SendMessages: false })
.catch(() => log.debug('Could not lock the closed ticket channel', { ticketId: ticket.id }));
} }
/** Grants a staff member access to the ticket channel (M6-T07). */ /** Grants a staff member access to the ticket channel (M6-T07). */
+85
View File
@@ -9,6 +9,7 @@ import {
} from 'discord.js'; } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js'; import { getAccessLevel } from '../../core/permissions.js';
@@ -525,6 +526,90 @@ export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GR
* (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast * (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast
* path, this sweep is the guarantee when an event is missed or a deletion failed. * path, this sweep is the guarantee when an event is missed or a deletion failed.
*/ */
/** Builds a matcher from a trigger template, `{user}` standing for any name. */
function templateMatcher(template) {
const escaped = String(template ?? DEFAULT_TEMPLATE).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`^${escaped.replace('\\{user\\}', '.+')}$`, 'u');
}
/**
* Takes back the generated channels the database no longer knows about (M14-T09).
*
* A channel outlives the process that made it: a restored backup, a wiped
* `data/` folder or a redeployment that ships a fresh database all leave real
* channels behind that nothing manages any more — they never get cleaned up and
* their owner can no longer rename or lock them.
*
* Only channels sitting in a trigger's own category and named after its
* template are taken, so a channel created by hand is never touched.
*/
export async function adoptOrphanVoiceChannels(client) {
let adopted = 0;
let removed = 0;
for (const guild of client.guilds.cache.values()) {
if (!readSetting('voice.adoptOrphans', guild.id)) continue;
let triggers = [];
try {
triggers = getVoiceTriggers(guild.id).filter((trigger) => trigger.enabled);
} catch (error) {
log.warn('Could not read the voice triggers', error);
continue;
}
if (triggers.length === 0) continue;
await guild.channels.fetch().catch(() => null);
for (const trigger of triggers) {
const triggerChannel = guild.channels.cache.get(trigger.triggerId);
const categoryId = trigger.categoryId || triggerChannel?.parentId;
if (!categoryId) continue;
const matches = templateMatcher(trigger.template);
for (const channel of guild.channels.cache.values()) {
if (channel.type !== ChannelType.GuildVoice) continue;
if (channel.parentId !== categoryId) continue;
if (channel.id === trigger.triggerId) continue;
if (getVoiceChannel(channel.id)) continue;
if (!matches.test(channel.name)) continue;
// Nobody left in it: it is a leftover, not something to hand back.
if (channel.members.size === 0) {
if (await deleteVoiceChannel(channel, 'Salon vocal temporaire orphelin et vide')) {
removed += 1;
logEvent({ guildId: guild.id, type: 'voice.orphan.removed', payload: { channelId: channel.id } });
}
continue;
}
// Still in use: give it back to whoever is in it, oldest member first.
const owner = channel.members.filter((member) => !member.user.bot).first() ?? channel.members.first();
addVoiceChannel({
channelId: channel.id,
guildId: guild.id,
ownerId: owner.id,
triggerId: trigger.triggerId,
name: channel.name,
userLimit: channel.userLimit ?? 0,
});
adopted += 1;
logEvent({
guildId: guild.id,
type: 'voice.orphan.adopted',
payload: { channelId: channel.id, ownerId: owner.id },
});
}
}
}
if (adopted > 0 || removed > 0) {
log.info('Recovered orphan voice channels', { adopted, removed });
}
return { adopted, removed };
}
export async function sweepVoiceChannels(client) { export async function sweepVoiceChannels(client) {
for (const guild of client.guilds.cache.values()) { for (const guild of client.guilds.cache.values()) {
let rows = []; let rows = [];
+41 -1
View File
@@ -1,6 +1,7 @@
import { ChannelType } from 'discord.js'; import { ChannelType, REST, Routes } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js'; import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { canActOn, getAccessLevel } from '../../core/permissions.js'; import { canActOn, getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
@@ -336,6 +337,45 @@ export function registerDiscordRoutes(router) {
{ access: ACCESS_LEVELS.STAFF }, { access: ACCESS_LEVELS.STAFF },
); );
/**
* Publishes the slash commands on the guild, what `npm run deploy:commands`
* does. Guild commands take effect immediately, so the result is visible in
* Discord as soon as this returns.
*/
router.post(
'/api/discord/commands/deploy',
async ({ context, actor }) => {
const commands = [...(context.client?.commands?.values() ?? [])];
if (commands.length === 0) throw badRequest('Aucune commande chargée : le bot n’est pas prêt.');
if (!env.discord.token || !env.discord.clientId || !env.discord.guildId) {
throw badRequest('`DISCORD_TOKEN`, `DISCORD_CLIENT_ID` et `DISCORD_GUILD_ID` sont requis.');
}
const body = commands.map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token);
try {
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), {
body,
});
} catch (error) {
log.error('Slash command deployment failed', error);
throw new ExternalApiError('discord', error.message ?? 'Publication refusée par Discord');
}
logEvent({
guildId: guildId(),
type: 'web.commands.deploy',
actorId: actor.userId,
payload: { count: body.length },
});
log.info('Slash commands deployed from the dashboard', { count: body.length, actor: actor.userId });
return { ok: true, count: body.length, names: body.map((command) => command.name).sort() };
},
{ access: ACCESS_LEVELS.OWNER },
);
/** Read-only inventory of the loaded slash commands and their required level. */ /** Read-only inventory of the loaded slash commands and their required level. */
router.get( router.get(
'/api/discord/commands', '/api/discord/commands',
+3
View File
@@ -14,6 +14,7 @@ import { registerOverviewRoutes } from './overview.js';
import { registerReleaseRoutes } from './releases.js'; import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js'; import { registerRepositoryRoutes } from './repositories.js';
import { registerSettingsRoutes } from './settings.js'; import { registerSettingsRoutes } from './settings.js';
import { registerWikiRoutes } from './wiki.js';
const here = path.dirname(fileURLToPath(import.meta.url)); const here = path.dirname(fileURLToPath(import.meta.url));
@@ -72,6 +73,8 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
registerAuthRoutes(router); registerAuthRoutes(router);
registerConfigurationRoutes(router); registerConfigurationRoutes(router);
// The public documentation stays reachable even while the bot is being set up.
registerWikiRoutes(router);
// Long-lived stream the pages listen to instead of polling (M16-T12). // Long-lived stream the pages listen to instead of polling (M16-T12).
router.get( router.get(
+19 -77
View File
@@ -11,7 +11,7 @@ import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { getDatabase } from '../../database/index.js'; import { getDatabase } from '../../database/index.js';
import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js'; import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js';
import { getSetting, setSetting } from '../../database/repositories/settings-repository.js'; import { GUILD_SETTINGS, SETTING_SECTIONS, allSettings, writeSetting } from '../../config/guild-settings.js';
import { import {
createApiToken, createApiToken,
deleteSession, deleteSession,
@@ -31,76 +31,21 @@ import { isOauthConfigured, redirectUri } from '../auth/discord-oauth.js';
const log = createLogger('web:settings'); const log = createLogger('web:settings');
const guildId = () => env.discord.guildId; const guildId = () => env.discord.guildId;
/** Guild settings the dashboard exposes as first-class switches. */ const readManaged = () => {
const MANAGED_SETTINGS = Object.freeze([ try {
{ return allSettings(guildId());
key: 'welcome.enabled', } catch {
label: 'Message de bienvenue', // The database is not ready: fall back to the declared defaults.
help: 'Publier un message dans le salon d’accueil à chaque arrivée.', return Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting.default]));
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) { export function registerSettingsRoutes(router) {
router.get( router.get(
'/api/settings', '/api/settings',
({ request, actor }) => ({ ({ request, actor }) => ({
schema: MANAGED_SETTINGS, schema: GUILD_SETTINGS,
sections: SETTING_SECTIONS,
values: readManaged(), values: readManaged(),
runtime: { runtime: {
nodeEnv: env.nodeEnv, nodeEnv: env.nodeEnv,
@@ -166,25 +111,22 @@ export function registerSettingsRoutes(router) {
router.put( router.put(
'/api/settings/values/:key', '/api/settings/values/:key',
({ params, body, actor }) => { ({ params, body, actor }) => {
const schema = MANAGED_SETTINGS.find((setting) => setting.key === params.key); if (!GUILD_SETTINGS.some((setting) => setting.key === params.key)) throw notFound('Réglage inconnu.');
if (!schema) throw notFound('Réglage inconnu.');
let value = body.value; let value;
if (schema.type === 'bool') value = Boolean(value); try {
else if (schema.type === 'enum') { value = writeSetting(params.key, body.value, { guildId: guildId(), updatedBy: actor.userId });
value = String(value); } catch (error) {
if (!schema.options.includes(value)) throw badRequest(error.message);
throw badRequest(`Valeurs possibles : ${schema.options.join(', ')}.`);
} }
setSetting(guildId(), schema.key, value, actor.userId);
logEvent({ logEvent({
guildId: guildId(), guildId: guildId(),
type: 'web.settings.update', type: 'web.settings.update',
actorId: actor.userId, actorId: actor.userId,
payload: { key: schema.key, value }, payload: { key: params.key, value },
}); });
return { key: schema.key, value }; return { key: params.key, value };
}, },
{ access: ACCESS_LEVELS.DEV }, { access: ACCESS_LEVELS.DEV },
); );
+209
View File
@@ -0,0 +1,209 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
createPage,
getPage,
getPageBySlug,
listAllPages,
listPublished,
removePage,
searchPublished,
updatePage,
} from '../../database/repositories/wiki-repository.js';
import { badRequest, forbidden, notFound } from '../http.js';
/**
* Public wiki, written from the dashboard (M17).
*
* The reading routes are deliberately open: a documentation nobody can reach
* without an account is not documentation. The writing routes sit behind the
* Dev level like the rest of the panel.
*/
const SLUG = /^[a-z0-9][a-z0-9-]{0,80}$/;
/** Shown in a listing: everything but the body, which can be long. */
const summarize = (page) => ({
slug: page.slug,
title: page.title,
summary: page.summary,
category: page.category,
position: page.position,
updatedAt: page.updated_at,
});
const full = (page) => ({ ...summarize(page), content: page.content });
const adminView = (page) => ({
id: page.id,
...full(page),
published: page.published,
protected: page.protected,
createdBy: page.created_by,
createdAt: page.created_at,
updatedBy: page.updated_by,
});
/** Categories in reading order, each with its pages. */
function tree(pages) {
const categories = [];
for (const page of pages) {
let category = categories.find((entry) => entry.name === page.category);
if (!category) categories.push((category = { name: page.category, pages: [] }));
category.pages.push(summarize(page));
}
return categories;
}
export function registerWikiRoutes(router) {
// --- Public ----------------------------------------------------------------
router.get(
'/api/wiki',
() => {
const pages = listPublished();
return {
site: {
title: 'Documentation FWS',
links: env.links,
},
categories: tree(pages),
count: pages.length,
};
},
{ public: true },
);
router.get(
'/api/wiki/pages/:slug',
({ params }) => {
const page = getPageBySlug(params.slug);
// A draft must not be readable by guessing its address.
if (!page || !page.published) throw notFound('Page introuvable.');
return full(page);
},
{ public: true },
);
router.get(
'/api/wiki/search',
({ query }) => {
const term = (query.get('q') ?? '').trim();
if (term.length < 2) return { results: [] };
return { results: searchPublished(term).map(summarize) };
},
{ public: true },
);
// --- Administration --------------------------------------------------------
router.get('/api/wiki/admin', () => ({ pages: listAllPages().map(adminView) }), {
access: ACCESS_LEVELS.STAFF,
});
router.get(
'/api/wiki/admin/:id',
({ params }) => {
const page = getPage(Number.parseInt(params.id, 10));
if (!page) throw notFound('Page introuvable.');
return adminView(page);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/wiki/admin',
({ body, actor }) => {
const slug = String(body.slug ?? '')
.trim()
.toLowerCase();
if (!SLUG.test(slug)) {
throw badRequest('Adresse invalide : minuscules, chiffres et tirets, 80 caractères maximum.');
}
if (getPageBySlug(slug)) throw badRequest(`Une page utilise déjà l’adresse « ${slug} ».`);
const title = String(body.title ?? '').trim();
if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.');
const page = createPage({
slug,
title,
summary: body.summary ? String(body.summary) : null,
content: String(body.content ?? ''),
category: String(body.category ?? '').trim() || 'Général',
position: Number.parseInt(body.position ?? 0, 10) || 0,
published: Boolean(body.published),
createdBy: actor.userId,
});
logEvent({
guildId: env.discord.guildId || null,
type: 'web.wiki.create',
actorId: actor.userId,
payload: { slug },
});
return adminView(page);
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/wiki/admin/:id',
({ params, body, actor }) => {
const page = getPage(Number.parseInt(params.id, 10));
if (!page) throw notFound('Page introuvable.');
const patch = {};
if (body.slug !== undefined) {
const slug = String(body.slug).trim().toLowerCase();
if (!SLUG.test(slug)) throw badRequest('Adresse invalide.');
const clash = getPageBySlug(slug);
if (clash && clash.id !== page.id) throw badRequest(`Une page utilise déjà l’adresse « ${slug} ».`);
patch.slug = slug;
}
if (body.title !== undefined) {
const title = String(body.title).trim();
if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.');
patch.title = title;
}
for (const key of ['summary', 'content', 'category']) {
if (body[key] !== undefined) patch[key] = String(body[key]);
}
if (body.position !== undefined) patch.position = body.position;
if (body.published !== undefined) patch.published = Boolean(body.published);
if (Object.keys(patch).length === 0) throw badRequest('Aucun champ modifiable fourni.');
const updated = updatePage(page.id, patch, actor.userId);
logEvent({
guildId: env.discord.guildId || null,
type: 'web.wiki.update',
actorId: actor.userId,
payload: { slug: updated.slug, fields: Object.keys(patch) },
});
return adminView(updated);
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/wiki/admin/:id',
({ params, actor }) => {
const page = getPage(Number.parseInt(params.id, 10));
if (!page) throw notFound('Page introuvable.');
if (page.protected) {
throw forbidden('Cette page est protégée : elle peut être réécrite, mais pas supprimée.');
}
removePage(page.id);
logEvent({
guildId: env.discord.guildId || null,
type: 'web.wiki.delete',
actorId: actor.userId,
payload: { slug: page.slug },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
}
+8
View File
@@ -68,6 +68,14 @@ const ROUTES = [
module: './views/community.js', module: './views/community.js',
level: LEVELS.STAFF, level: LEVELS.STAFF,
}, },
{
path: 'wiki',
icon: '📖',
label: 'Wiki',
group: 'Communauté',
module: './views/wiki.js',
level: LEVELS.STAFF,
},
{ {
path: 'logs', path: 'logs',
icon: '≡', icon: '≡',
+168
View File
@@ -0,0 +1,168 @@
/**
* Markdown renderer for the wiki (M17).
*
* Deliberately small: headings, lists, tables, code, quotes, links, emphasis.
* Everything is HTML-escaped **before** any transformation runs, so a page can
* never inject markup — the pages are written by the team, but a renderer that
* relies on that is one mistake away from being a hole.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
export const slugify = (text) =>
String(text)
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
/** Inline pass, applied to text that is already escaped. */
function inline(text) {
return text
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(
/!\[([^\]]*)\]\(([^)\s]+)\)/g,
(_, alt, src) => `<img src="${src}" alt="${alt}" loading="lazy" />`,
)
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, href) => {
// Only http(s) and in-page anchors: no `javascript:` sneaking through.
const safe = /^(https?:\/\/|\/|#)/.test(href) ? href : '#';
const external = safe.startsWith('http');
return `<a href="${safe}"${external ? ' target="_blank" rel="noreferrer noopener"' : ''}>${label}</a>`;
})
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>')
.replace(/~~([^~]+)~~/g, '<del>$1</del>');
}
const cells = (line) =>
line
.trim()
.replace(/^\||\|$/g, '')
.split('|')
.map((cell) => inline(cell.trim()));
/**
* Renders a page and returns `{ html, headings }`, the headings feeding the
* table of contents.
*/
export function render(markdown) {
const lines = escape(markdown).split('\n');
const out = [];
const headings = [];
let index = 0;
const closeList = (stack) => {
while (stack.length > 0) out.push(`</${stack.pop()}>`);
};
const listStack = [];
while (index < lines.length) {
const line = lines[index];
// Fenced code, kept verbatim.
if (/^\s*```/.test(line)) {
closeList(listStack);
const body = [];
index += 1;
while (index < lines.length && !/^\s*```/.test(lines[index])) body.push(lines[index++]);
index += 1;
out.push(`<pre><code>${body.join('\n')}</code></pre>`);
continue;
}
// Table: a header row followed by a separator row.
if (line.includes('|') && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[index + 1] ?? '')) {
closeList(listStack);
const header = cells(line);
index += 2;
const rows = [];
while (index < lines.length && lines[index].includes('|') && lines[index].trim() !== '') {
rows.push(cells(lines[index++]));
}
out.push(
`<div class="table-wrap"><table class="table"><thead><tr>${header
.map((cell) => `<th>${cell}</th>`)
.join('')}</tr></thead><tbody>${rows
.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join('')}</tr>`)
.join('')}</tbody></table></div>`,
);
continue;
}
const heading = /^(#{1,4})\s+(.*)$/.exec(line);
if (heading) {
closeList(listStack);
const level = heading[1].length;
const text = heading[2].trim();
const id = slugify(text);
if (level <= 3) headings.push({ id, text, level });
out.push(`<h${level} id="${id}">${inline(text)}</h${level}>`);
index += 1;
continue;
}
if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
closeList(listStack);
out.push('<hr />');
index += 1;
continue;
}
const quote = /^&gt;\s?(.*)$/.exec(line);
if (quote) {
closeList(listStack);
const body = [quote[1]];
index += 1;
while (index < lines.length && /^&gt;\s?/.test(lines[index])) {
body.push(lines[index++].replace(/^&gt;\s?/, ''));
}
out.push(`<blockquote>${inline(body.join(' '))}</blockquote>`);
continue;
}
const bullet = /^\s*[-*]\s+(.*)$/.exec(line);
const ordered = /^\s*\d+\.\s+(.*)$/.exec(line);
if (bullet || ordered) {
const tag = bullet ? 'ul' : 'ol';
if (listStack.at(-1) !== tag) {
closeList(listStack);
out.push(`<${tag}>`);
listStack.push(tag);
}
out.push(`<li>${inline((bullet ?? ordered)[1])}</li>`);
index += 1;
continue;
}
if (line.trim() === '') {
closeList(listStack);
index += 1;
continue;
}
// Paragraph: consecutive non-empty lines are joined.
closeList(listStack);
const paragraph = [line];
index += 1;
while (
index < lines.length &&
lines[index].trim() !== '' &&
!/^\s*([-*]\s|\d+\.\s|#{1,4}\s|&gt;|```)/.test(lines[index]) &&
!lines[index].includes('|')
) {
paragraph.push(lines[index++]);
}
out.push(`<p>${inline(paragraph.join(' '))}</p>`);
}
closeList(listStack);
return { html: out.join('\n'), headings };
}
+28 -4
View File
@@ -1,5 +1,29 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="FWS Linux">
<rect width="64" height="64" rx="14" fill="#0f1720" /> <title>FWS Linux</title>
<path d="M32 10 12 52h9l11-24 11 24h9z" fill="#1793d1" /> <!-- Official FWS mark: cyan ring on a dark navy disc. -->
<circle cx="32" cy="40" r="5" fill="#8fd3ff" /> <circle cx="100" cy="100" r="100" fill="#1b2130" />
<circle cx="100" cy="100" r="92" fill="none" stroke="#22d3ee" stroke-width="7" />
<text
x="100"
y="103"
fill="#22d3ee"
font-family="'Segoe UI', 'Helvetica Neue', Arial, sans-serif"
font-size="62"
font-weight="700"
letter-spacing="1"
text-anchor="middle"
>
FWS
</text>
<text
x="100"
y="143"
fill="#c9ced6"
font-family="ui-monospace, 'JetBrains Mono', Menlo, Consolas, monospace"
font-size="22"
letter-spacing="1.5"
text-anchor="middle"
>
Linux
</text>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 235 B

After

Width:  |  Height:  |  Size: 779 B

+40 -15
View File
@@ -1,21 +1,22 @@
/* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */ /* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */
:root { :root {
--blue: #1793d1; /* Official FWS mark: cyan ring on dark navy. */
--blue-soft: #8fd3ff; --blue: #22d3ee;
--blue-soft: #7fe7f8;
--green: #2ecc71; --green: #2ecc71;
--amber: #f1c40f; --amber: #f1c40f;
--red: #e74c3c; --red: #e74c3c;
--violet: #9b59b6; --violet: #9b59b6;
--gitea: #609926; --gitea: #609926;
--bg: #0b1016; --bg: #10141f;
--bg-elevated: #121a24; --bg-elevated: #171c2b;
--bg-sunken: #080d12; --bg-sunken: #0c1018;
--surface: #16202c; --surface: #1b2130;
--border: #23303f; --border: #2a3145;
--text: #e6edf3; --text: #e6ebf3;
--text-muted: #8da2b6; --text-muted: #8f98ad;
--shadow: 0 10px 30px rgb(0 0 0 / 35%); --shadow: 0 10px 30px rgb(0 0 0 / 35%);
--radius: 12px; --radius: 12px;
@@ -392,7 +393,7 @@ pre code {
.btn-primary { .btn-primary {
background: var(--blue); background: var(--blue);
border-color: var(--blue); border-color: var(--blue);
color: #04121c; color: #0c1018;
} }
.btn-primary:hover:not(:disabled) { .btn-primary:hover:not(:disabled) {
filter: brightness(1.1); filter: brightness(1.1);
@@ -496,7 +497,7 @@ pre code {
} }
.toggle input:checked + .toggle-track::after { .toggle input:checked + .toggle-track::after {
transform: translateX(16px); transform: translateX(16px);
background: #04121c; background: #0c1018;
} }
.toggle input:focus-visible + .toggle-track { .toggle input:focus-visible + .toggle-track {
outline: 2px solid var(--blue-soft); outline: 2px solid var(--blue-soft);
@@ -690,6 +691,15 @@ pre code {
padding-left: 1.2rem; padding-left: 1.2rem;
} }
.wiki-preview {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.9rem;
background: var(--bg-sunken);
max-height: 20rem;
overflow-y: auto;
}
.build { .build {
font-size: 0.7rem; font-size: 0.7rem;
padding: 0 0.2rem; padding: 0 0.2rem;
@@ -777,7 +787,7 @@ body[data-mode='simple'] .advanced-only {
} }
.mode-switch button.active { .mode-switch button.active {
background: var(--blue); background: var(--blue);
color: #04121c; color: #0c1018;
} }
/* --- Login and setup ------------------------------------------------------ */ /* --- Login and setup ------------------------------------------------------ */
@@ -854,7 +864,7 @@ body[data-mode='simple'] .advanced-only {
.wizard-step.done .dot { .wizard-step.done .dot {
background: var(--green); background: var(--green);
border-color: var(--green); border-color: var(--green);
color: #04121c; color: #0c1018;
} }
.wizard-step.invalid .dot { .wizard-step.invalid .dot {
background: var(--red); background: var(--red);
@@ -944,9 +954,24 @@ body[data-mode='simple'] .advanced-only {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.45rem; gap: 0.45rem;
color: inherit;
text-decoration: none;
cursor: pointer;
transition:
border-color 0.12s ease,
transform 0.12s ease;
} }
.repo-card h3 a { .repo-card:hover {
color: var(--text); border-color: var(--blue);
text-decoration: none;
transform: translateY(-1px);
}
.repo-card:focus-visible {
outline: 2px solid var(--blue);
outline-offset: 2px;
}
.repo-card h3 {
color: var(--blue-soft);
} }
.repo-meta { .repo-meta {
display: flex; display: flex;
+27 -2
View File
@@ -4,6 +4,7 @@ import {
badge, badge,
button, button,
card, card,
confirmAction,
field, field,
grid, grid,
input, input,
@@ -397,8 +398,32 @@ export async function render(host, { state }) {
notificationsCard(guild, level), notificationsCard(guild, level),
card( card(
'Commandes', 'Commandes slash',
{ advanced: true, subtitle: 'Commandes slash chargées et niveau requis.' }, {
subtitle: 'Commandes chargées par le bot et niveau requis pour chacune.',
actions:
level >= LEVELS.OWNER &&
button(
'Publier sur Discord',
async () => {
if (
!(await confirmAction(
'Publier les commandes',
'Les commandes chargées remplacent celles enregistrées sur le serveur. L’effet est immédiat.',
))
) {
return;
}
const result = await api.post('/api/discord/commands/deploy', {});
toast(`${result.count} commande(s) publiée(s) sur le serveur.`);
},
{ tone: 'primary' },
),
},
h('p', {
class: 'muted',
text: 'À relancer après chaque ajout ou modification de commande — l’équivalent de `npm run deploy:commands`.',
}),
await renderCommands(), await renderCommands(),
), ),
), ),
+5 -3
View File
@@ -28,10 +28,12 @@ const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
// --- List ------------------------------------------------------------------- // --- List -------------------------------------------------------------------
function repositoryCard(repository) { function repositoryCard(repository) {
// The card is the link: clicking anywhere on it opens the repository, which
// is what a rectangle that reacts to the pointer promises.
return h( return h(
'article', 'a',
{ class: 'repo-card' }, { class: 'repo-card', href: `#/repos/${repository.fullName}` },
h('h3', {}, h('a', { href: `#/repos/${repository.fullName}`, text: repository.name })), h('h3', { text: repository.name }),
h('p', { class: 'muted', text: repository.description || 'Sans description.' }), h('p', { class: 'muted', text: repository.description || 'Sans description.' }),
h( h(
'div', 'div',
+79 -35
View File
@@ -33,47 +33,91 @@ const keyValue = (rows) =>
rows, rows,
); );
function behaviourCard(data, level, reload) { /** One control per setting, typed after its declaration. */
if (level < LEVELS.DEV) { function settingControl(setting, value, apply) {
return card( if (setting.type === 'bool') {
'Comportement du bot', return h(
{ subtitle: 'Lecture seule : le niveau Dev est requis pour modifier ces réglages.' }, 'div',
keyValue( {},
data.schema.map((setting) => ({ toggle(Boolean(value), apply, setting.label),
label: setting.label, h('div', { class: 'field-help', text: setting.help }),
value: String(data.values[setting.key]),
})),
),
); );
} }
return card( if (setting.type === 'enum') {
'Comportement du bot', return field(
{ subtitle: 'Appliqué immédiatement, sans redémarrage.' }, setting.label,
...data.schema.map((setting) => { select(
const apply = async (value) => { setting.options.map((option) => ({ value: option, label: option })),
await api.put(`/api/settings/values/${setting.key}`, { value }); { value, onChange: (event) => apply(event.target.value) },
toast(`« ${setting.label} » enregistré.`); ),
}; { help: setting.help },
);
}
if (setting.type === 'bool') { const control = input({
return h( value: value ?? '',
'div', type: setting.type === 'int' ? 'number' : 'text',
{}, min: setting.min,
toggle(Boolean(data.values[setting.key]), apply, setting.label), max: setting.max,
h('div', { class: 'field-help', text: setting.help }), maxlength: setting.maxLength,
); placeholder: String(setting.default ?? ''),
} });
return field(
setting.label, // Text fields save on blur rather than on every keystroke.
select( const commit = () => apply(setting.type === 'int' ? Number(control.value) : control.value);
setting.options.map((option) => ({ value: option, label: option })), control.addEventListener('change', commit);
{ value: data.values[setting.key], onChange: (event) => apply(event.target.value) }, control.addEventListener('keydown', (event) => {
), if (event.key === 'Enter') control.blur();
{ help: setting.help }, });
return field(setting.label, control, { help: setting.help });
}
function behaviourCard(data, level, reload) {
const editable = level >= LEVELS.DEV;
const sections = data.sections ?? [];
return h(
'div',
{ class: 'stack' },
...sections.map((section) => {
const settings = data.schema.filter((setting) => setting.section === section.id);
if (settings.length === 0) return null;
return card(
section.title,
{ subtitle: section.summary },
...settings.map((setting) => {
const value = data.values[setting.key];
if (!editable) {
return h(
'div',
{ class: setting.advanced ? 'advanced-only' : '' },
h('strong', { text: `${setting.label} : ` }),
h('span', { text: String(value) }),
h('div', { class: 'field-help', text: setting.help }),
);
}
const apply = async (next) => {
try {
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
toast(`« ${setting.label} » enregistré.`);
data.values[setting.key] = saved.value;
} catch (error) {
toast(error.message, 'error');
}
};
const node = settingControl(setting, value, apply);
if (setting.advanced) node.classList.add('advanced-only');
return node;
}),
); );
}), }),
button('Recharger', reload, { tone: 'ghost' }), editable && button('Recharger les réglages', reload, { tone: 'ghost' }),
); );
} }
+240
View File
@@ -0,0 +1,240 @@
import { api } from '../core/api.js';
import { formatRelative, h } from '../core/dom.js';
import { autoRefresh } from '../core/live.js';
import { render as renderMarkdown } from '../core/markdown.js';
import {
badge,
button,
card,
confirmAction,
field,
input,
notice,
renderAsync,
table,
textarea,
toast,
toggle,
} from '../core/ui.js';
/** Editing the public documentation from the panel (M17). */
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
const slugify = (text) =>
text
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 80);
/**
* Editor with a live preview: legal pages are long, and writing Markdown blind
* is how broken tables end up published.
*/
async function editPage(existing, reload) {
const title = input({ value: existing?.title ?? '', placeholder: 'Titre de la page' });
const slug = input({ value: existing?.slug ?? '', placeholder: 'adresse-de-la-page' });
const summary = input({ value: existing?.summary ?? '', placeholder: 'Une phrase de résumé' });
const category = input({ value: existing?.category ?? 'Général', placeholder: 'Général' });
const position = input({ type: 'number', value: existing?.position ?? 0 });
const content = textarea({ value: existing?.content ?? '', style: { minHeight: '22rem' } });
let published = existing?.published ?? false;
// A new page gets its address from its title until the address is touched.
let slugTouched = Boolean(existing);
slug.addEventListener('input', () => (slugTouched = true));
title.addEventListener('input', () => {
if (!slugTouched) slug.value = slugify(title.value);
});
const preview = h('div', { class: 'wiki-content' });
const refreshPreview = () => {
preview.innerHTML = renderMarkdown(content.value).html;
};
content.addEventListener('input', refreshPreview);
refreshPreview();
const showPreview = h('div', { class: 'wiki-preview' }, preview);
showPreview.hidden = true;
const { modal } = await import('../core/ui.js');
const confirmed = await modal(
existing ? `Modifier « ${existing.title} »` : 'Nouvelle page',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Titre', title),
field('Adresse', slug, { help: 'Minuscules, chiffres et tirets. Visible dans l’URL : /wiki/…' }),
field('Résumé', summary, { help: 'Affiché sous le titre et dans les résultats de recherche.' }),
field('Catégorie', category, { help: 'Regroupe les pages dans le menu du site public.' }),
field('Position', position, { help: 'Ordre dans la catégorie, du plus petit au plus grand.' }),
field('Contenu (Markdown)', content),
button(
'Afficher / masquer l’aperçu',
() => {
showPreview.hidden = !showPreview.hidden;
refreshPreview();
},
{ tone: 'ghost' },
),
showPreview,
toggle(published, (checked) => (published = checked), 'Publier (visible par tout le monde)'),
existing?.protected &&
notice('Page protégée : son contenu est modifiable, mais elle ne peut pas être supprimée.', 'info'),
),
submit: () => title.value.trim().length >= 2 && slug.value.trim() !== '',
}),
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
);
if (!confirmed) return;
const payload = {
title: title.value.trim(),
slug: slug.value.trim(),
summary: summary.value.trim(),
category: category.value.trim() || 'Général',
position: Number(position.value) || 0,
content: content.value,
published,
};
try {
if (existing) await api.patch(`/api/wiki/admin/${existing.id}`, payload);
else await api.post('/api/wiki/admin', payload);
toast(existing ? 'Page enregistrée.' : 'Page créée.');
reload();
} catch (error) {
toast(error.message, 'error');
}
}
export function render(host, { state }) {
const level = state.me.accessLevel;
const reload = () => render(host, { state });
autoRefresh(reload, { topics: ['mutation'] });
return renderAsync(
host,
() => api.get('/api/wiki/admin'),
(data) => {
const published = data.pages.filter((page) => page.published).length;
return h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('h1', { text: 'Wiki' }),
h('p', {
class: 'muted',
text: 'Documentation publique, écrite ici et lisible sans compte sur /wiki.',
}),
),
h(
'div',
{ class: 'row' },
h('a', {
class: 'btn btn-ghost',
href: '/wiki',
target: '_blank',
rel: 'noreferrer',
text: '↗ Voir le site',
}),
level >= LEVELS.DEV && button('Nouvelle page', () => editPage(null, reload), { tone: 'primary' }),
),
),
published === 0 &&
notice('Aucune page publiée : le site public affichera une documentation vide.', 'warning'),
card(
'Pages',
{ subtitle: `${data.pages.length} page(s), dont ${published} publiée(s)` },
table(
[
{
label: 'Page',
render: (page) =>
h(
'div',
{},
h('strong', { text: page.title }),
h('div', { class: 'muted', text: page.summary || `/wiki/${page.slug}` }),
),
},
{ label: 'Catégorie', render: (page) => badge(page.category, 'info') },
{ label: 'Ordre', className: 'num advanced-only', key: 'position' },
{
label: 'État',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published ? badge('Publiée', 'success') : badge('Brouillon', 'neutral'),
page.protected && badge('Protégée', 'warning'),
),
},
{
label: 'Modifiée',
className: 'nowrap',
render: (page) => formatRelative(page.updatedAt),
},
{
label: '',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published &&
h('a', {
class: 'btn btn-ghost btn-sm',
href: `/wiki/${page.slug}`,
target: '_blank',
rel: 'noreferrer',
text: 'Voir',
}),
level >= LEVELS.DEV &&
button('Modifier', () => editPage(page, reload), { tone: 'ghost' }),
level >= LEVELS.DEV &&
button(
page.published ? 'Dépublier' : 'Publier',
async () => {
await api.patch(`/api/wiki/admin/${page.id}`, { published: !page.published });
toast(page.published ? 'Page dépubliée.' : 'Page publiée.');
reload();
},
{ tone: page.published ? 'ghost' : 'success' },
),
level >= LEVELS.OWNER &&
!page.protected &&
button(
'Supprimer',
async () => {
if (!(await confirmAction('Supprimer la page', `Supprimer « ${page.title} » ?`))) {
return;
}
await api.delete(`/api/wiki/admin/${page.id}`);
toast('Page supprimée.');
reload();
},
{ tone: 'danger' },
),
),
},
],
data.pages,
{ empty: 'Aucune page.' },
),
),
);
},
);
}
+198
View File
@@ -0,0 +1,198 @@
/* Public documentation site — reuses the dashboard tokens from styles.css (M17). */
.wiki-body {
background: var(--bg);
}
.wiki-shell {
display: grid;
grid-template-columns: 270px minmax(0, 1fr);
max-width: 1280px;
margin: 0 auto;
min-height: 100vh;
}
.wiki-side {
border-right: 1px solid var(--border);
padding: 1.2rem 1rem;
display: flex;
flex-direction: column;
gap: 0.8rem;
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
}
.wiki-brand {
display: flex;
align-items: center;
gap: 0.6rem;
color: var(--text);
}
.wiki-brand:hover {
text-decoration: none;
}
.wiki-brand strong {
display: block;
font-size: 1rem;
}
.wiki-brand span {
display: block;
font-size: 0.75rem;
color: var(--text-muted);
}
.wiki-nav,
.wiki-results {
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.wiki-nav a,
.wiki-results a {
display: block;
padding: 0.38rem 0.6rem;
border-radius: var(--radius-sm);
color: var(--text);
font-size: 0.88rem;
}
.wiki-nav a:hover,
.wiki-results a:hover {
background: var(--surface);
text-decoration: none;
}
.wiki-nav a.active {
background: color-mix(in srgb, var(--blue) 16%, transparent);
color: var(--blue-soft);
font-weight: 600;
box-shadow: inset 3px 0 0 var(--blue);
}
.wiki-main {
padding: 2rem 2.4rem 4rem;
min-width: 0;
}
.wiki-article {
display: grid;
grid-template-columns: minmax(0, 1fr) 200px;
gap: 2rem;
align-items: start;
}
.wiki-article h1 {
font-size: 2rem;
margin-bottom: 0.4rem;
}
.wiki-summary {
color: var(--text-muted);
font-size: 1.02rem;
margin-bottom: 1.4rem;
}
/* Comfortable measure: long legal text is unreadable across a full screen. */
.wiki-content {
max-width: 72ch;
font-size: 0.97rem;
line-height: 1.7;
}
.wiki-content h2 {
font-size: 1.32rem;
margin: 2rem 0 0.7rem;
padding-top: 0.6rem;
border-top: 1px solid var(--border);
}
.wiki-content h3 {
font-size: 1.08rem;
margin: 1.4rem 0 0.5rem;
}
.wiki-content h4 {
font-size: 0.97rem;
margin: 1.1rem 0 0.4rem;
color: var(--text-muted);
}
.wiki-content p {
margin: 0 0 0.9rem;
}
.wiki-content ul,
.wiki-content ol {
margin: 0 0 1rem;
padding-left: 1.35rem;
}
.wiki-content li {
margin-bottom: 0.35rem;
}
.wiki-content blockquote {
margin: 1rem 0;
padding: 0.7rem 1rem;
border-left: 3px solid var(--blue);
background: var(--surface);
border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
color: var(--text-muted);
}
.wiki-content hr {
border: none;
border-top: 1px solid var(--border);
margin: 2rem 0;
}
.wiki-content img {
max-width: 100%;
border-radius: var(--radius-sm);
}
.wiki-content .table-wrap {
margin-bottom: 1.2rem;
}
.wiki-toc {
position: sticky;
top: 2rem;
display: flex;
flex-direction: column;
gap: 0.1rem;
border-left: 1px solid var(--border);
padding-left: 0.9rem;
}
.wiki-toc a {
font-size: 0.8rem;
color: var(--text-muted);
padding: 0.18rem 0;
}
.wiki-toc a:hover {
color: var(--text);
text-decoration: none;
}
.wiki-toc a[data-level='3'] {
padding-left: 0.7rem;
}
.wiki-updated {
margin-top: 2.5rem;
padding-top: 0.8rem;
border-top: 1px solid var(--border);
font-size: 0.8rem;
}
@media (max-width: 1080px) {
.wiki-article {
grid-template-columns: minmax(0, 1fr);
}
.wiki-toc {
display: none;
}
}
@media (max-width: 860px) {
.wiki-shell {
grid-template-columns: 1fr;
}
.wiki-side {
position: static;
height: auto;
border-right: none;
border-bottom: 1px solid var(--border);
}
.wiki-main {
padding: 1.2rem 1rem 3rem;
}
}
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="fr" data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<meta name="description" content="Documentation publique de l'organisation open source FWS." />
<title>Documentation FWS</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/styles.css" />
<link rel="stylesheet" href="/wiki.css" />
</head>
<body class="wiki-body">
<div id="wiki">
<noscript>Cette documentation nécessite JavaScript.</noscript>
</div>
<script type="module" src="/wiki.js"></script>
</body>
</html>
+183
View File
@@ -0,0 +1,183 @@
import { h, mount, qs } from './core/dom.js';
import { render as renderMarkdown } from './core/markdown.js';
/**
* Public documentation site (M17).
*
* Standalone on purpose: no session, no dashboard shell, and its own small
* bundle — a visitor reading the privacy notice should never meet a login page.
*/
const state = { tree: null, slug: null, theme: localStorage.getItem('fws.theme') ?? 'dark' };
const api = async (path) => {
const response = await fetch(path, { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error((await response.json().catch(() => null))?.error ?? 'Page introuvable.');
return response.json();
};
const currentSlug = () => {
const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/\/$/, '');
return decodeURIComponent(path) || null;
};
function navigate(slug, { replace = false } = {}) {
const url = slug ? `/wiki/${encodeURIComponent(slug)}` : '/wiki';
if (replace) window.history.replaceState({}, '', url);
else window.history.pushState({}, '', url);
draw();
}
function sidebar() {
const search = h('input', {
class: 'input',
type: 'search',
placeholder: 'Rechercher…',
'aria-label': 'Rechercher dans la documentation',
});
const results = h('div', { class: 'wiki-results' });
let timer = null;
search.addEventListener('input', () => {
clearTimeout(timer);
const term = search.value.trim();
if (term.length < 2) {
mount(results);
return;
}
timer = setTimeout(async () => {
const { results: found } = await api(`/api/wiki/search?q=${encodeURIComponent(term)}`).catch(() => ({
results: [],
}));
mount(
results,
found.length === 0
? h('p', { class: 'muted', text: 'Aucun résultat.' })
: found.map((page) =>
h('a', {
href: `/wiki/${page.slug}`,
text: page.title,
onClick: (event) => {
event.preventDefault();
search.value = '';
mount(results);
navigate(page.slug);
},
}),
),
);
}, 250);
});
return h(
'aside',
{ class: 'wiki-side' },
h(
'a',
{ class: 'wiki-brand', href: '/wiki' },
h('img', { src: '/favicon.svg', alt: '', width: 36, height: 36 }),
h('div', {}, h('strong', { text: 'FWS' }), h('span', { text: 'Documentation' })),
),
search,
results,
h(
'nav',
{ class: 'wiki-nav' },
(state.tree?.categories ?? []).map((category) =>
h(
'div',
{},
h('div', { class: 'nav-group', text: category.name }),
category.pages.map((page) =>
h('a', {
href: `/wiki/${page.slug}`,
text: page.title,
class: page.slug === state.slug ? 'active' : '',
onClick: (event) => {
event.preventDefault();
navigate(page.slug);
},
}),
),
),
),
),
);
}
function tableOfContents(headings) {
if (headings.length < 2) return null;
return h(
'nav',
{ class: 'wiki-toc' },
h('div', { class: 'nav-group', text: 'Sur cette page' }),
headings.map((heading) =>
h('a', { href: `#${heading.id}`, text: heading.text, dataset: { level: String(heading.level) } }),
),
);
}
async function article(host) {
const slug = state.slug ?? state.tree?.categories?.[0]?.pages?.[0]?.slug ?? null;
if (!slug) {
mount(host, h('p', { class: 'empty', text: 'Aucune page publiée pour l’instant.' }));
return;
}
let page;
try {
page = await api(`/api/wiki/pages/${encodeURIComponent(slug)}`);
} catch (error) {
mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message })));
return;
}
document.title = `${page.title} · Documentation FWS`;
const { html, headings } = renderMarkdown(page.content);
const body = h('div', { class: 'wiki-content' });
body.innerHTML = html;
mount(
host,
h(
'div',
{ class: 'wiki-article' },
h(
'article',
{},
h('p', { class: 'muted', text: page.category }),
h('h1', { text: page.title }),
page.summary && h('p', { class: 'wiki-summary', text: page.summary }),
body,
h('footer', {
class: 'muted wiki-updated',
text: `Dernière modification : ${new Date(`${page.updatedAt}Z`).toLocaleDateString('fr-FR', {
dateStyle: 'long',
})}`,
}),
),
tableOfContents(headings),
),
);
}
async function draw() {
state.slug = currentSlug();
const root = qs('#wiki');
if (!state.tree) {
state.tree = await api('/api/wiki').catch(() => ({ categories: [], site: {} }));
}
const main = h('main', { class: 'wiki-main' });
mount(root, h('div', { class: 'wiki-shell' }, sidebar(), main));
await article(main);
// In-page anchors only work once the article is on screen.
if (window.location.hash) qs(window.location.hash)?.scrollIntoView({ block: 'start' });
}
document.documentElement.dataset.theme = state.theme;
window.addEventListener('popstate', draw);
draw();
+13 -3
View File
@@ -11,6 +11,7 @@ import { authorize } from './auth/guard.js';
import { broadcast, closeEventStreams, topicForPath } from './events.js'; import { broadcast, closeEventStreams, topicForPath } from './events.js';
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
import { createRouter } from './router.js'; import { createRouter } from './router.js';
import { seedWiki } from './services/wiki-seed.js';
/** HTTP server of the dashboard (M16-T01). */ /** HTTP server of the dashboard (M16-T01). */
@@ -71,9 +72,10 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/'); const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
if (!isApi) { if (!isApi) {
// Anything else is the single page application; unknown paths fall back to // The wiki is a separate public page: it must never fall back to the
// its shell so client-side routing works on a hard refresh. // dashboard shell, which would send a visitor to a login screen.
const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' }); const fallback = pathname === '/wiki' || pathname.startsWith('/wiki/') ? 'wiki.html' : 'index.html';
const served = await sendStatic(response, publicDir, pathname, { fallback });
if (!served) sendEmpty(response, 404); if (!served) sendEmpty(response, 404);
return; return;
} }
@@ -128,6 +130,14 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
} }
export function startWebServer({ client = null, setupOnly = false } = {}) { export function startWebServer({ client = null, setupOnly = false } = {}) {
// A bot that processes personal data owes its users a notice, so the legal
// pages are created before the site answers its first request.
try {
seedWiki();
} catch (error) {
log.warn('Could not seed the wiki', error);
}
const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() })); const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() }));
server.listen(env.web.port, env.web.host, () => { server.listen(env.web.port, env.web.host, () => {
+249
View File
@@ -0,0 +1,249 @@
import { createLogger } from '../../core/logger.js';
import { countPages, createPage, getPageBySlug } from '../../database/repositories/wiki-repository.js';
/**
* Pages the wiki ships with (M17).
*
* The two legal ones are seeded because a bot that processes personal data owes
* its users a notice, and an empty wiki makes that easy to forget. They are
* marked `protected`, so they can be rewritten but not deleted by accident.
*
* They describe what this codebase actually stores — nothing aspirational — but
* the organisation still has to fill in the bracketed details and have them
* reviewed. This is a starting point written from the schema, not legal advice.
*/
const log = createLogger('wiki');
const TERMS = `## 1. Objet
Ces conditions régissent l'utilisation du bot Discord **FWS-Bot** et de son tableau de bord, exploités par **[NOM DE L'ENTITÉ RESPONSABLE]** (ci-après « nous »).
Utiliser le bot — une commande, un ticket, un sondage, un salon vocal généré — vaut acceptation de ces conditions. Si tu n'en acceptes pas les termes, n'utilise pas le bot.
## 2. Service fourni
Le bot propose de l'assistance communautaire, des tickets de support, de la modération, des sondages, des salons vocaux temporaires et une intégration avec notre forge Gitea.
Le service est fourni **en l'état**, gratuitement et sans garantie de disponibilité. Nous pouvons le modifier, l'interrompre ou l'arrêter à tout moment, notamment pour maintenance ou pour des raisons de sécurité.
## 3. Règles d'utilisation
En utilisant le bot, tu t'engages à :
- respecter le règlement du serveur Discord ainsi que les [Conditions d'utilisation de Discord](https://discord.com/terms) ;
- ne pas tenter d'accéder à des fonctions réservées à l'équipe, ni de contourner les contrôles d'accès ;
- ne pas automatiser, surcharger ou perturber le service ;
- ne pas publier, via le bot, de contenu illicite, haineux, diffamatoire ou portant atteinte aux droits de tiers ;
- ne pas utiliser les tickets pour transmettre des données sensibles au sens de l'art. 5 let. c LPD (santé, opinions religieuses ou politiques, données biométriques, etc.).
## 4. Modération
L'équipe peut avertir, exclure temporairement, expulser ou bannir un compte qui ne respecte pas ces règles. Les sanctions sont consignées et consultables par l'équipe. Tu peux contester une sanction en ouvrant un ticket ou en écrivant à l'adresse indiquée au point 8.
## 5. Contenus que tu publies
Tu restes titulaire de ce que tu écris. Tu nous accordes le droit d'afficher, de stocker et de traiter ces contenus dans la stricte mesure nécessaire au fonctionnement du service.
## 6. Responsabilité
Dans les limites permises par le droit suisse, notre responsabilité est exclue pour les dommages indirects, la perte de données et l'indisponibilité du service. Rien dans ces conditions n'exclut la responsabilité en cas de faute intentionnelle ou de négligence grave.
Le bot dépend de services tiers (Discord, notre instance Gitea, l'hébergeur). Nous ne répondons pas de leurs interruptions.
## 7. Modification des conditions
Nous pouvons modifier ces conditions. La version applicable est celle publiée sur cette page ; les changements importants sont annoncés sur le serveur Discord. Continuer d'utiliser le bot après une modification vaut acceptation.
## 8. Droit applicable et contact
Ces conditions sont soumises au **droit suisse**. Le for est à **[LIEU DU SIÈGE]**, sous réserve des fors impératifs.
Contact : **[ADRESSE DE CONTACT]**
_Dernière mise à jour : à compléter lors de la première relecture._
`;
const PRIVACY = `Cette politique explique quelles données personnelles le bot traite, pourquoi, et quels droits tu as. Elle est rédigée conformément à la **loi fédérale sur la protection des données (LPD, RS 235.1)** révisée, en vigueur depuis le 1er septembre 2023, et à son ordonnance (OPDo).
## 1. Responsable du traitement
**[NOM DE L'ENTITÉ RESPONSABLE]**
[ADRESSE POSTALE]
[ADRESSE DE CONTACT]
Nous n'avons pas désigné de conseiller à la protection des données au sens de l'art. 10 LPD ; les demandes sont traitées à l'adresse ci-dessus.
## 2. Données traitées
Le bot ne collecte que ce dont il a besoin pour fonctionner. Concrètement :
### Sur Discord
| Donnée | Quand | Pourquoi |
| --- | --- | --- |
| Identifiant Discord, pseudo, nom affiché, avatar | À chaque interaction | Identifier l'auteur d'une action et afficher un nom lisible |
| Identifiants de serveur, de salon et de rôles | En continu | Appliquer les droits et publier au bon endroit |
| Tickets : catégorie, auteur, personne en charge, dates, motif de clôture | À l'ouverture et à la clôture | Assurer le suivi du support |
| Sanctions : type, personne visée, personne qui sanctionne, motif, durée | À chaque sanction | Tenir un historique de modération et traiter les contestations |
| Sondages : question, choix, et **le vote de chaque personne** | À chaque vote | Compter les voix et empêcher les votes multiples |
| Salons vocaux générés : propriétaire, nom, verrouillage, limite | Tant que le salon existe | Rendre la personne maîtresse de son salon |
| Journal d'événements : type d'action, auteur, horodatage | À chaque action notable | Traçabilité, sécurité, diagnostic |
### Sur le tableau de bord
| Donnée | Quand | Pourquoi |
| --- | --- | --- |
| Identifiant, pseudo, nom affiché, avatar Discord | À la connexion | Authentifier et afficher qui est connecté |
| Rôles sur le serveur | À la connexion | Déterminer le niveau d'accès |
| Adresse IP et agent utilisateur | Pendant la session | Sécurité, détection d'un accès anormal |
| Empreinte du jeton de session | Pendant la session | Maintenir la connexion sans stocker le jeton lui-même |
### Ce que nous ne traitons pas
- **Le contenu de tes messages Discord** : le bot ne demande pas l'autorisation \`Message Content\` et ne lit donc pas tes messages.
- **Aucune donnée sensible** au sens de l'art. 5 let. c LPD n'est collectée volontairement. Merci de ne pas en transmettre dans un ticket.
- **Aucun profilage** et **aucune décision individuelle automatisée** au sens de l'art. 21 LPD : toute sanction est décidée par une personne.
## 3. Finalités
Les traitements servent exclusivement à : faire fonctionner le service, modérer la communauté, assurer le support, garantir la sécurité du système, et diagnostiquer les incidents.
Il n'y a **ni publicité, ni revente, ni transmission commerciale** de données.
## 4. Base du traitement
Le traitement repose sur l'exécution du service que tu demandes en utilisant le bot, ainsi que sur notre intérêt légitime à sécuriser et modérer la communauté (art. 31 LPD). Lorsqu'un consentement est requis, il est demandé explicitement.
## 5. Destinataires et sous-traitants
| Destinataire | Rôle | Localisation |
| --- | --- | --- |
| Discord Inc. | Plateforme sur laquelle le bot fonctionne | États-Unis |
| [HÉBERGEUR] | Hébergement du bot et de sa base de données | [PAYS] |
| Notre instance Gitea | Issues, pull requests, releases | [PAYS] |
Aucune donnée n'est transmise à d'autres tiers, sauf obligation légale.
## 6. Communication à l'étranger
Discord traite des données aux **États-Unis**. Cette communication a lieu conformément aux art. 16 et 17 LPD, sur la base des garanties contractuelles et des décisions d'adéquation applicables. En utilisant Discord, tu es de toute façon déjà soumis à sa propre [politique de confidentialité](https://discord.com/privacy).
## 7. Durée de conservation
| Donnée | Conservation |
| --- | --- |
| Journal d'événements | Purgé automatiquement selon \`LOG_RETENTION_DAYS\` (30 jours par défaut) |
| Sessions du tableau de bord | Expirent automatiquement, 12 heures par défaut |
| Tickets | Conservés pour le suivi, effaçables sur demande |
| Sanctions | Conservées tant qu'elles restent pertinentes pour la modération |
| Salons vocaux | Supprimés en même temps que le salon |
| Journaux techniques | Fichiers quotidiens, purgés selon la même durée de rétention |
## 8. Sécurité
Conformément à l'art. 8 LPD, nous prenons des mesures techniques et organisationnelles appropriées :
- accès au tableau de bord restreint aux rôles Staff, Dev et Owner du serveur ;
- jetons de session et jetons d'API stockés sous forme d'empreinte, jamais en clair ;
- secrets masqués automatiquement dans les journaux ;
- webhooks signés en HMAC-SHA256 et vérifiés à temps constant ;
- base de données locale, non exposée publiquement, sauvegardable.
## 9. Tes droits
Selon la LPD, tu peux à tout moment :
- **demander l'accès** à tes données (art. 25 LPD) ;
- **faire rectifier** une donnée inexacte (art. 32 LPD) ;
- **demander l'effacement** de tes données, sous réserve de ce que nous devons conserver ;
- **t'opposer** à un traitement ;
- **obtenir la remise** de tes données dans un format courant (art. 28 LPD).
Écris à **[ADRESSE DE CONTACT]** ou ouvre un ticket. Nous répondons en principe dans les 30 jours. La demande est gratuite ; une pièce d'identité peut être demandée en cas de doute sérieux sur ton identité.
Tu peux aussi t'adresser au **Préposé fédéral à la protection des données et à la transparence (PFPDT)**, Feldeggweg 1, 3003 Berne — [edoeb.admin.ch](https://www.edoeb.admin.ch).
## 10. Violations de données
En cas de violation de la sécurité entraînant un risque élevé pour tes droits, nous annonçons l'incident au PFPDT dans les meilleurs délais (art. 24 LPD) et t'informons lorsque la loi l'exige.
## 11. Modifications
Cette politique peut évoluer. La version applicable est celle publiée ici, et les changements importants sont annoncés sur le serveur Discord.
_Dernière mise à jour : à compléter lors de la première relecture._
---
> ⚠️ **À faire relire.** Ce texte décrit fidèlement ce que le code traite, mais les mentions entre crochets doivent être complétées et l'ensemble validé par une personne compétente avant publication.
`;
const WELCOME = `Bienvenue sur la documentation publique de **FWS**.
Ces pages sont rédigées et publiées depuis le tableau de bord du bot : elles n'ont besoin d'aucun dépôt séparé ni d'aucune étape de compilation.
## Pour commencer
- **Conditions d'utilisation** — ce à quoi tu t'engages en utilisant le bot.
- **Politique de confidentialité** — quelles données sont traitées, pourquoi, et tes droits.
## Contribuer
Cette documentation est modifiable par l'équipe depuis **Tableau de bord → Wiki**. Une page peut rester en brouillon le temps d'être écrite, puis être publiée en un clic.
`;
/** Pages created on first start, and re-created if a protected one goes missing. */
const DEFAULT_PAGES = [
{
slug: 'accueil',
title: 'Accueil',
summary: 'Point d’entrée de la documentation publique FWS.',
category: 'Général',
position: 0,
content: WELCOME,
published: true,
isProtected: false,
},
{
slug: 'conditions-utilisation',
title: 'Conditions d’utilisation',
summary: 'Ce à quoi tu t’engages en utilisant le bot FWS.',
category: 'Légal',
position: 10,
content: TERMS,
published: true,
isProtected: true,
},
{
slug: 'politique-confidentialite',
title: 'Politique de confidentialité',
summary: 'Données traitées, durées de conservation et droits, selon la LPD suisse.',
category: 'Légal',
position: 20,
content: PRIVACY,
published: true,
isProtected: true,
},
];
/**
* Creates the default pages when they are missing.
* Existing pages are never overwritten: the organisation's own wording wins.
*/
export function seedWiki() {
let created = 0;
for (const page of DEFAULT_PAGES) {
// The welcome page is only offered on a genuinely empty wiki; the legal ones
// come back whenever they are absent.
if (!page.isProtected && countPages() > 0) continue;
if (getPageBySlug(page.slug)) continue;
createPage({ ...page, createdBy: 'system' });
created += 1;
}
if (created > 0) log.info('Seeded the wiki with its default pages', { created });
return created;
}
+143
View File
@@ -0,0 +1,143 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import {
GUILD_SETTINGS,
SETTING_SECTIONS,
allSettings,
readSetting,
validateSetting,
writeSetting,
} from '../src/config/guild-settings.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
const GUILD = 'guild-1';
describe('settings schema', () => {
it('places every setting in a declared section', () => {
const sections = new Set(SETTING_SECTIONS.map((section) => section.id));
for (const setting of GUILD_SETTINGS) {
assert.ok(sections.has(setting.section), `${setting.key} points at an unknown section`);
}
});
it('documents every setting and gives it a default', () => {
for (const setting of GUILD_SETTINGS) {
assert.ok(setting.label?.length > 0, `${setting.key} has no label`);
assert.ok(setting.help?.length > 0, `${setting.key} has no help`);
assert.notEqual(setting.default, undefined, `${setting.key} has no default`);
}
});
it('uses unique keys', () => {
const keys = GUILD_SETTINGS.map((setting) => setting.key);
assert.equal(new Set(keys).size, keys.length);
});
/**
* A switch that nothing reads is worse than no switch: it promises a
* behaviour the bot does not have.
*/
it('is read by the code for every key it declares', async () => {
const { readFile, readdir } = await import('node:fs/promises');
const path = await import('node:path');
const files = [];
const walk = async (directory) => {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) await walk(target);
else if (entry.name.endsWith('.js')) files.push(target);
}
};
await walk('src');
const sources = (await Promise.all(files.map((file) => readFile(file, 'utf8')))).join('\n');
for (const setting of GUILD_SETTINGS) {
assert.ok(
sources.includes(`'${setting.key}'`),
`${setting.key} is declared but never read by the code`,
);
}
});
});
describe('settings validation', () => {
it('accepts a boolean and refuses anything else', () => {
assert.equal(validateSetting('welcome.enabled', true), null);
assert.match(validateSetting('welcome.enabled', 'oui'), /vrai ou faux/);
});
it('enforces the numeric bounds', () => {
assert.equal(validateSetting('moderation.defaultMuteMinutes', 30), null);
assert.match(validateSetting('moderation.defaultMuteMinutes', 0), /Minimum/);
assert.match(validateSetting('moderation.banDeleteMessageHours', 200), /Maximum/);
assert.match(validateSetting('moderation.defaultMuteMinutes', 'beaucoup'), /entier/);
});
it('restricts an enum to its options', () => {
assert.equal(validateSetting('web.defaultMode', 'advanced'), null);
assert.match(validateSetting('web.defaultMode', 'expert'), /Valeurs possibles/);
});
it('accepts an empty snowflake, meaning « none »', () => {
assert.equal(validateSetting('notifications.mentionRoleId', ''), null);
assert.equal(validateSetting('notifications.mentionRoleId', '123456789012345678'), null);
assert.match(validateSetting('notifications.mentionRoleId', 'abc'), /17 à 20 chiffres/);
});
it('caps the length of a free text', () => {
assert.equal(validateSetting('welcome.message', 'Bonjour'), null);
assert.match(validateSetting('welcome.message', 'x'.repeat(501)), /500 caractères/);
});
it('rejects an unknown key', () => {
assert.match(validateSetting('nope', true), /inconnu/);
});
});
describe('settings storage', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM guild_settings;'));
it('falls back to the declared default', () => {
assert.equal(readSetting('welcome.enabled', GUILD), true);
assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 60);
assert.equal(readSetting('notifications.mentionRoleId', GUILD), '');
});
it('stores then reads a value back with its type', () => {
writeSetting('welcome.enabled', false, { guildId: GUILD });
writeSetting('moderation.defaultMuteMinutes', 15, { guildId: GUILD });
assert.equal(readSetting('welcome.enabled', GUILD), false);
assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 15);
});
it('refuses to store an invalid value', () => {
assert.throws(() => writeSetting('web.defaultMode', 'expert', { guildId: GUILD }), /Valeurs possibles/);
assert.equal(readSetting('web.defaultMode', GUILD), 'simple');
});
it('keeps each guild apart', () => {
writeSetting('welcome.enabled', false, { guildId: GUILD });
assert.equal(readSetting('welcome.enabled', 'other-guild'), true);
});
it('coerces a value stored out of bounds back into range', () => {
getDatabase()
.prepare('INSERT INTO guild_settings (guild_id, key, value) VALUES (?, ?, ?)')
.run(GUILD, 'moderation.defaultMuteMinutes', '999999');
assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 40_320);
});
it('returns every setting at once', () => {
const values = allSettings(GUILD);
assert.equal(Object.keys(values).length, GUILD_SETTINGS.length);
assert.equal(values['welcome.enabled'], true);
});
it('rejects an unknown key rather than storing it', () => {
assert.throws(() => writeSetting('nope', true, { guildId: GUILD }), /Unknown guild setting/);
});
});
+215
View File
@@ -0,0 +1,215 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
createPage,
getPageBySlug,
listPublished,
removePage,
searchPublished,
updatePage,
} from '../src/database/repositories/wiki-repository.js';
import { render } from '../src/web/public/core/markdown.js';
import { createHandler } from '../src/web/server.js';
import { seedWiki } from '../src/web/services/wiki-seed.js';
/** Public wiki and its Markdown renderer (M17). */
describe('markdown renderer', () => {
it('escapes HTML before doing anything else', () => {
const { html } = render('<script>alert(1)</script>');
assert.doesNotMatch(html, /<script>/);
assert.match(html, /&lt;script&gt;/);
});
it('escapes HTML inside a heading and a table cell too', () => {
assert.doesNotMatch(render('## <img src=x onerror=1>').html, /<img src=x/);
assert.doesNotMatch(render('| a |\n| --- |\n| <b>x</b> |').html, /<b>x<\/b>/);
});
it('refuses a javascript: link', () => {
const { html } = render('[clique](javascript:alert(1))');
assert.doesNotMatch(html, /javascript:/);
assert.match(html, /href="#"/);
});
it('keeps http links and opens them in a new tab', () => {
const { html } = render('[Discord](https://discord.com/terms)');
assert.match(html, /href="https:\/\/discord\.com\/terms"/);
assert.match(html, /rel="noreferrer noopener"/);
});
it('renders headings with anchors and collects them', () => {
const { html, headings } = render('## Durée de conservation\n### Détail');
assert.match(html, /<h2 id="duree-de-conservation">/);
assert.deepEqual(
headings.map((heading) => heading.id),
['duree-de-conservation', 'detail'],
);
});
it('renders a table', () => {
const { html } = render('| Donnée | Quand |\n| --- | --- |\n| Pseudo | À la connexion |');
assert.match(html, /<th>Donnée<\/th>/);
assert.match(html, /<td>À la connexion<\/td>/);
});
it('renders lists, quotes and fenced code verbatim', () => {
assert.match(render('- un\n- deux').html, /<ul>\n<li>un<\/li>/);
assert.match(render('1. un\n2. deux').html, /<ol>\n<li>un<\/li>/);
assert.match(render('> attention').html, /<blockquote>attention<\/blockquote>/);
assert.match(render('```\nnpm run setup\n```').html, /<pre><code>npm run setup<\/code><\/pre>/);
});
it('renders inline code and emphasis', () => {
const { html } = render('Voir `LOG_RETENTION_DAYS` et **le reste**.');
assert.match(html, /<code>LOG_RETENTION_DAYS<\/code>/);
assert.match(html, /<strong>le reste<\/strong>/);
});
it('survives an empty page', () => {
assert.deepEqual(render(''), { html: '', headings: [] });
assert.deepEqual(render(undefined), { html: '', headings: [] });
});
});
describe('wiki repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM wiki_pages;'));
const page = (overrides = {}) =>
createPage({ slug: 'guide', title: 'Guide', content: 'Bonjour', published: true, ...overrides });
it('stores and reads a page back', () => {
const created = page();
assert.equal(created.published, true);
assert.equal(created.protected, false);
assert.deepEqual(getPageBySlug('guide'), created);
});
it('lists only the published pages, in reading order', () => {
page({ slug: 'b', title: 'B', category: 'Général', position: 2 });
page({ slug: 'a', title: 'A', category: 'Général', position: 1 });
page({ slug: 'draft', title: 'Brouillon', published: false });
assert.deepEqual(
listPublished().map((entry) => entry.slug),
['a', 'b'],
);
});
it('searches titles and bodies', () => {
page({ slug: 'vie-privee', title: 'Confidentialité', content: 'Conservation des données' });
assert.equal(searchPublished('conservation').length, 1);
assert.equal(searchPublished('introuvable').length, 0);
});
it('refuses to delete a protected page', () => {
const locked = page({ slug: 'legal', isProtected: true });
assert.equal(removePage(locked.id), 0);
assert.ok(getPageBySlug('legal'));
});
it('records who last changed a page', () => {
const created = page();
const updated = updatePage(created.id, { title: 'Guide revu' }, 'u1');
assert.equal(updated.title, 'Guide revu');
assert.equal(updated.updated_by, 'u1');
});
});
describe('wiki seeding', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM wiki_pages;'));
it('creates the welcome page and both legal pages', () => {
assert.equal(seedWiki(), 3);
assert.ok(getPageBySlug('conditions-utilisation').published);
assert.ok(getPageBySlug('politique-confidentialite').published);
});
it('marks the legal pages as protected', () => {
seedWiki();
assert.equal(getPageBySlug('politique-confidentialite').protected, true);
assert.equal(getPageBySlug('accueil').protected, false);
});
it('names the Swiss law it is written against', () => {
seedWiki();
const privacy = getPageBySlug('politique-confidentialite').content;
assert.match(privacy, /LPD/);
assert.match(privacy, /PFPDT/);
assert.match(privacy, /art\. 25 LPD/);
});
it('never overwrites what the organisation has written', () => {
seedWiki();
updatePage(getPageBySlug('conditions-utilisation').id, { content: 'Notre propre texte.' });
assert.equal(seedWiki(), 0);
assert.equal(getPageBySlug('conditions-utilisation').content, 'Notre propre texte.');
});
it('brings a deleted legal page back, but not the welcome one', () => {
seedWiki();
getDatabase().exec("DELETE FROM wiki_pages WHERE slug IN ('politique-confidentialite', 'accueil')");
assert.equal(seedWiki(), 1);
assert.ok(getPageBySlug('politique-confidentialite'));
assert.equal(getPageBySlug('accueil'), null);
});
});
describe('wiki over HTTP', () => {
let app;
before(async () => {
initDatabase(':memory:');
seedWiki();
app = createServer(createHandler({ client: null, setupOnly: false }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
closeDatabase();
});
const get = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('serves the page tree without a session', async () => {
const response = await get('/api/wiki');
const body = await response.json();
assert.equal(response.status, 200);
assert.ok(body.categories.some((category) => category.name === 'Légal'));
});
it('serves a published page without a session', async () => {
const response = await get('/api/wiki/pages/conditions-utilisation');
assert.equal(response.status, 200);
assert.match((await response.json()).content, /droit suisse/);
});
it('hides a draft even when its address is known', async () => {
createPage({ slug: 'secret', title: 'Secret', content: 'chut', published: false });
assert.equal((await get('/api/wiki/pages/secret')).status, 404);
});
it('searches without a session', async () => {
const body = await get('/api/wiki/search?q=confidentialite').then((response) => response.json());
assert.ok(Array.isArray(body.results));
});
it('keeps the administration behind the login', async () => {
assert.equal((await get('/api/wiki/admin')).status, 401);
});
it('serves its own page rather than the dashboard shell', async () => {
const body = await get('/wiki/conditions-utilisation').then((response) => response.text());
assert.match(body, /wiki\.js/);
assert.doesNotMatch(body, /id="app"/);
});
});