Author SHA1 Message Date
BlackAngelTV ffb54a8e37 chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 21:14:00 +02:00
BlackAngelTV e6ce594b34 fix(rules): show the rules field with a save button and edit the message
The rules lived in a card of their own that never showed up next to the
settings, so the section read as an empty toggle nobody could fill in. The
markdown now renders as a real field with an "Enregistrer" button, and
saving edits the message already pinned instead of deleting it and
posting a new one: same link, same place, pin kept.
2026-09-25 21:14:00 +02:00
BlackAngelTV 22e9723700 chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 20:44:36 +02:00
BlackAngelTV 31c0fc861a feat(rules): write the rules from the dashboard and republish them
The rules lived in a channel nobody but a staff member with a shell could
edit, and the welcome message pointed at it. They are now written in
markdown under Settings and published as a single pinned embed, and a new
publication deletes the message the bot posted last time instead of
piling copies up in the channel.
2026-09-25 20:44:29 +02:00
BlackAngelTV 20ffbbacad Merge pull request 'Fix/mute log wording' (#147) from fix/mute-log-wording into main
CI / quality (push) Has been cancelled
Reviewed-on: #147
2026-09-25 18:34:31 +00:00
BlackAngelTV c61a13176e chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
2026-09-25 20:29:32 +02:00
BlackAngelTV 44e990d04b docs(agents): update the repository conventions and commit rules
The instructions now speak of a dépôt rather than a repo, point at
CONTRIBUTING.md for the collaboration conventions, require signed commits
and state how a commit asked for by the maintainer must be written.
2026-09-25 20:29:31 +02:00
BlackAngelTV 99e1fd2723 fix(moderation): tell a mute apart from a kick in the logs
A timeout was filed as "Exclusion temporaire" right next to "Expulsion",
so a sanction could not be read back from the log channel, the direct
message or `/mod logs`. Each action now carries its own emoji and wording
behind a single label, used by every surface.
2026-09-25 20:29:19 +02:00
BlackAngelTV 859b229181 Merge pull request 'Feat/add missing commands' (#146) from feat/add-missing-commands into main
CI / quality (push) Has been cancelled
Reviewed-on: #146
2026-09-25 18:13:58 +00:00
BlackAngelTV d720c0a17e chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-25 20:11:05 +02:00
BlackAngelTV 9f8ac0d29e feat(moderation): add the unmute and unban commands
A sanction could be applied but never lifted from Discord, so undoing a
mistake meant leaving the bot for the server settings. Both lifts are
recorded next to the sanctions they lift, which means widening the
moderation history CHECK constraint through a table rebuild.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-25 20:11:00 +02:00
nocode b8be549fda Merge branch 'feat/web-dashboard'
CI / quality (push) Has been cancelled
2026-09-24 20:53:31 +02:00
nocodeandClaude Opus 5 b9bc3b934b chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:36 +02:00
nocodeandClaude Opus 5 566af4db70 docs(web): document my tasks, the search and the status page
Adds the chapter the three tools were missing, and points the monitoring
guide at /api/status rather than /api/health, which answers a narrower
question than an operator usually means.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:35 +02:00
nocodeandClaude Opus 5 a1e1de7734 feat(web): publish a public status page at /status
Checking whether the service is up required an account, so the answer
lived where the people asking could not reach it.

The page is rendered on the server with no script at all and refreshes
through a meta tag: a status page that needs a working browser is
useless at the moment it is read. Two rules follow from it being public.
A repository the forge does not list as public keeps its environment
visible but loses its name, and the banner always states the worst true
thing — a failed deployment forbids the green headline even while the
bot answers. WEB_PUBLIC_STATUS=false removes page and route together.

/api/status gives the same in JSON, which is what a monitor should watch
rather than /api/health — the latter only says the process is alive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:26 +02:00
nocodeandClaude Opus 5 9acb523510 feat(web): search the whole panel from one place
Finding anything meant knowing which tab it lived in — fine once you
have learned the panel, hopeless before. ⌘K now covers cards,
repositories, issues, wiki pages and members at once.

Pages are matched in the browser, so the palette answers before it has
asked the server and stays useful while the forge is down. Each remote
source is queried independently and a source that fails is simply absent
from the results, rather than taking the others with it. Issues come
from one organization-wide request: per repository, the palette could
not afford them on every keystroke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:04 +02:00
nocodeandClaude Opus 5 fcc82d82d6 feat(projects): gather the cards one member carries
A board answers "where does the work stand". Nobody opens a dashboard to
ask that first: they ask what is on them today, and once the work is
spread over several boards no single board can answer it.

The cards assigned to a member are now listed on a page of their own,
grouped by deadline, with a counter on the sidebar entry — a page you
have to open to know whether it needs you is a page you stop opening.
The column travels with each card, so finishing one from the list is a
single move rather than a detour through its board.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:45:03 +02:00
nocodeandClaude Opus 5 d2256e2211 refactor(web): extract the build marker into its own module
The version and the interface build date were computed inside the route
file, where two copies of the same comment had already drifted apart. The
status page needs the same answer, and a second copy would eventually
give a different one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:43:41 +02:00
nocodeandClaude Opus 5 e3ce266225 docs(ops): correct the deployment path for a panel without a shell
Pterodactyl's console is the process stdin, not a terminal, so the previous
instructions could not be followed even with full panel rights. The chapter
now covers both cases: a real shell where one exists, and otherwise the
dashboard's own command deploy, which runs inside the container and needs no
console at all.

It also starts by checking the commands land on the filesystem the bot
reads — a pull in the wrong place reports success and changes nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:11:51 +02:00
nocodeandClaude Opus 5 1643fcb591 docs(ops): document deployment, CI, monitoring and backups
Four independent procedures, each opening with the failure it prevents —
most of them ones this project actually hit: a front-end older than its API
after a partial upload, a broken card move that no test ran before it
shipped, an evening spent asking whether the site was down, and a database
that came back empty after a rebuild.

The CI workflow ships with them. It leaves out `format:check`, which would
fail on CRLF files that predate the Prettier configuration; normalising them
deserves a commit of its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:08:52 +02:00
nocodeandClaude Opus 5 1c21f6ff53 feat(projects): pull Gitea issues onto any board
The import only existed on a repository board and always landed in the first
column. The organization board is exactly where issues from several
repositories belong together, so the button now lives on every board and
asks which repository, which column, and whether closed issues come too.

An issue already on the board is skipped rather than duplicated, so the
button survives being pressed twice — which the tests check against a
stand-in forge, along with the due date and labels carried over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:03:06 +02:00
nocodeandClaude Opus 5 8869c74b7b fix(wiki): render the public pages on the server
The documentation was assembled in the browser, so a client that runs no
script saw an empty shell — including whoever fetches the terms and privacy
links before approving an application, which is exactly what those pages are
for.

The wiki is now delivered as finished HTML, carries no script at all, and
declares itself indexable, unlike the panel. Search works through a plain
query string, an unknown page answers 404 rather than a blank page, and both
legal pages are linked from the footer of every page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:31:27 +02:00
nocodeandClaude Opus 5 3d0e21d7cb feat(wiki): serve the legal pages at /terms-of-service and /privacy-policy
Discord, and most platforms, ask for a terms URL and a privacy URL in a
form field; pasting a `/wiki/...` address there reads like an afterthought.
Both pages now answer at the root, while everything else stays under
`/wiki/`.

The API states each page's address instead of leaving the front to rebuild
it, so there is one place that decides. Existing pages are renamed rather
than recreated, keeping whatever has already been written in them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:25:59 +02:00
nocodeandClaude Opus 5 e1b9a5cc77 feat(projects): add the board interface
Drag and drop between columns, cards carrying an assignee, a due date,
labels and a linked issue whose state shows on the card. An overloaded
column says so in its header rather than blocking the drop.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:09 +02:00
nocodeandClaude Opus 5 901ca56959 feat(projects): add a Kanban board per repository and one for the organization
Boards live in SQLite rather than in Gitea, whose project API is not stable
across versions: a board that stops working whenever the forge hiccups is
worse than no board, and this one has hiccupped already.

A card can still point at an issue — `owner/repo#12` — and its real state is
resolved when the forge answers, one request per repository rather than per
card. Open issues can also be imported in bulk, skipping those already on
the board.

Columns follow the ones the README describes, and carry an optional card
limit which warns rather than refuses: stopping someone mid-gesture to
enforce a convention is not what a limit is for.

Moving a card rebuilds the order explicitly — take the column without it,
insert at the wanted rank, renumber — because fractional positions get the
same-column case wrong, as the tests showed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 b793298cbf test(web): lock the sidebar highlighting behind tests
It has been reported twice and fixed twice by reading the code, which is how
it came back. The decision is now a module of its own — the shell only asks
it which entry is current — and twelve cases pin it down: a detail page, a
query string, every spelling of the home route, and the original regression
where home stayed lit everywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 3f4a5709cf fix(web): stop caching the interface modules
Modules cache independently, so a browser could revalidate one and keep an
older copy of another — leaving a page running one version of itself and a
different version of its helpers. That surfaces as an error inside a
feature, which is nothing like what it is, and no reload short of clearing
the site data reliably fixes it.

A dashboard is a handful of small files read by one person at a time: the
bandwidth caching saves is worth less than the failure it causes. They are
now fetched fresh.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 c031b4d9e2 fix(web): keep the stack when a view fails
Views caught their errors and showed only the message, so nothing said which
module or which line had failed — neither in the console, which never saw
the error, nor on the page.

The stack is now logged and offered on the page behind a disclosure, because
opening the developer console is not always an option on a self-hosted
panel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 92c27aed9f fix(web): read the interface build date instead of freezing it at startup
The marker was captured once at import, while the front-end is served from
disk on every request. Uploading new files therefore left it announcing the
old build until the next restart — the exact confusion it was added to
prevent.

It is now read from disk, cached ten seconds so a health check does not walk
the tree each time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 75d1e53205 fix(web): stop the settings page breaking on an unexpected payload
Every list the page walks was read straight off the response, so a single
missing field took the whole view down with `undefined.map` — which reads as
a broken feature rather than as what it is, a page and an API disagreeing on
the shape of the data.

The page now normalises what it receives: absent lists render empty, an enum
without options falls back to a text field, and settings that arrive without
sections are shown under one heading instead of not at all.

Errors of that family also say so, and point at the reload that fixes them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 95b51ab428 feat(web): open a repository from anywhere on its row
The cards on the repository page already opened as a whole, but the tables
on the organisation and overview pages still only linked the name, so the
same object behaved differently depending on where it was listed.

A table row can now carry a destination. Controls inside it keep their own
behaviour, the row is reachable with the keyboard, and only the empty space
navigates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 539b1506f4 fix(web): give static assets a validator caches can check
The front-end was served with `no-cache` but no `ETag` and no
`Last-Modified`, so a cache had nothing to revalidate against and could keep
handing out modules older than the API they talk to — which surfaces as a
cryptic error in a view rather than as anything resembling a stale cache.

Assets now carry both, and an unchanged file answers 304.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 3bd290cba6 fix(web): say when the dashboard is disabled
`WEB_ENABLED` not being `true` produced no output at all, so a missing site
looked exactly like a broken one and there was nothing in the console to
tell the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 afcd0e55bc fix(web): say out loud when the dashboard cannot listen
A failed `listen` only produced a generic line the bot then carried on past,
so the site was simply absent with nothing explaining why — and inside a
container a bind on an unpublished port succeeds while staying unreachable,
which looks identical to a crash from the browser.

The error now names the address, the port and the actual cause, and a
successful bind on `0.0.0.0` reminds that the port still has to be published
by the host.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 40032ec091 fix(config): warn when a public address is announced but only loopback is bound
`WEB_HOST=127.0.0.1` is the right default behind a reverse proxy on the same
machine, and the wrong one inside a container or on a hosting panel, where
the process has to bind the allocation. The guidance only mentioned the
first case, so a `.env` written from the wizard could leave the dashboard
listening where nothing could reach it — every request timing out with
nothing saying why.

The wizard now flags the contradiction between a loopback bind and a public
URL, and both the help text and `.env.example` name the container case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 5660235f3d 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 23:20:06 +02:00
nocodeandClaude Opus 5 e5b7303a01 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 23:20:06 +02:00
nocodeandClaude Opus 5 c76c0b96eb 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 23:20:06 +02:00
nocodeandClaude Opus 5 621f3e404b 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 23:20:06 +02:00
nocodeandClaude Opus 5 e397abcfcd 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 23:20:06 +02:00
nocodeandClaude Opus 5 262274473a 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 23:20:05 +02:00
nocodeandClaude Opus 5 b42fb1065a 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 23:20:05 +02:00
nocodeandClaude Opus 5 406b5af3ea 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 23:20:05 +02:00
86 changed files with 8604 additions and 316 deletions

No files matched your search

+6 -2
View File
@@ -75,8 +75,9 @@ GITEA_WEBHOOK_SECRET=
# Site d'administration servi par le bot : `npm run setup` pour l'assistant .env, # Site d'administration servi par le bot : `npm run setup` pour l'assistant .env,
# puis http://WEB_HOST:WEB_PORT une fois le bot démarré. # puis http://WEB_HOST:WEB_PORT une fois le bot démarré.
WEB_ENABLED=false WEB_ENABLED=false
# 127.0.0.1 par défaut : n'expose rien hors de la machine. Mettre 0.0.0.0 seulement # 127.0.0.1 derrière un reverse proxy installé sur la même machine.
# derrière un reverse proxy HTTPS. # 0.0.0.0 dans un conteneur ou sur un panel d'hébergement (Pterodactyl, Docker) :
# sinon le site n'écoute que sur la boucle locale et reste injoignable.
WEB_HOST=127.0.0.1 WEB_HOST=127.0.0.1
WEB_PORT=3080 WEB_PORT=3080
# URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord. # URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord.
@@ -91,6 +92,9 @@ DISCORD_CLIENT_SECRET=
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord. # Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
# À vider une fois le .env rempli. # À vider une fois le .env rempli.
WEB_SETUP_TOKEN= WEB_SETUP_TOKEN=
# Publie /status : bot en ligne, derniers déploiements, dernières releases.
# Les dépôts privés n'y apparaissent jamais par leur nom.
WEB_PUBLIC_STATUS=true
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement). # Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
WEB_ALLOW_COMMAND_DEPLOYS=false WEB_ALLOW_COMMAND_DEPLOYS=false
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2). # Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
+35
View File
@@ -0,0 +1,35 @@
name: CI
# Lint and tests on every push and every pull request. `format:check` is
# deliberately absent: the repository still holds CRLF files that predate the
# Prettier configuration, so the step would fail on untouched code. Normalise
# the line endings in a commit of their own, then add it here.
on:
push:
branches: [main]
pull_request:
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- name: Installer les dépendances
run: npm ci
- name: Lint
run: npm run lint
- name: Tests
run: npm test
# The changelog is generated from the commit history, so a stale one is
# a real defect rather than a formatting detail.
- name: Changelog à jour
run: npm run changelog:check
+22 -15
View File
@@ -1,12 +1,12 @@
# AGENTS.md — Instructions pour les agents IA # AGENTS.md — Instructions pour les agents IA
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un repo de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` apporte le contexte complet. > Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un dépôt de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` présente l'organisation et le `CONTRIBUTING.md` détaille les conventions de collaboration.
## Contexte ## Contexte
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack (pas de restriction de langage). - **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack technique (sans restriction de langage).
- Projet principal : **FWS Arch** — un fork d'Arch Linux avec une surcouche conviviale pour simplifier l'installation et l'usage au quotidien. - Projet principal : **FWS ISO** — une distribution Linux basée sur Arch Linux, pensée pour simplifier l'installation et l'usage au quotidien.
- Conventions détaillées : `README.md` (FR) / `README.en.md` (EN). - Conventions détaillées : `CONTRIBUTING.md` (FR) / `CONTRIBUTING.en.md` (EN).
## Règles à respecter ## Règles à respecter
@@ -24,29 +24,36 @@
### Code & commentaires ### Code & commentaires
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite, documenter le non-évident (choix d'implémentation, trade-offs, cas limites). - Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite ; documenter le non-évident (choix d'implémentation, compromis, cas limites).
- Respecter la stack et les conventions existantes du repo avant d'ajouter de nouvelles dépendances. - Respecter la stack technique et les conventions existantes du dépôt avant d'ajouter de nouvelles dépendances.
### Fichiers sensibles (`.gitignore`) ### Fichiers sensibles (`.gitignore`)
- Ne **jamais** committer : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets. - Ne **jamais** versionner : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
- Un `.gitignore` doit exister à la racine de chaque repo. - Un `.gitignore` doit exister à la racine de chaque dépôt.
### Tests ### Tests
- Fichiers de test : `*.test.*`, noms `describe` / `it` en anglais. - Fichiers de test : `*.test.*` ; noms de tests `describe` / `it` en anglais.
- Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée. - Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée.
### Issues & signalement de bugs ### Issues & signalement de bugs
- Les bugs et demandes sont suivis via les **issues**, liées au tableau Kanban. - Les bugs et demandes sont suivis via les **issues** et, lorsqu'il existe, le tableau Kanban du projet.
- Une PR qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`). - Une pull request qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
- Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur. - Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur.
### Commits demandés par l'utilisateur
- Lorsque l'utilisateur demande explicitement de créer un commit, l'IA doit le faire après avoir vérifié les changements et les contrôles disponibles, sans attendre une confirmation supplémentaire.
- Le titre et le corps du commit ne doivent jamais mentionner l'IA, l'assistant, Codebuff ou l'outil utilisé.
- Ne pas ajouter l'IA comme auteur ou co-auteur dans le message du commit.
## Bonnes pratiques pour un agent ## Bonnes pratiques pour un agent
- Lire `AGENTS.md` puis `README.md` avant d'éditer du code. - Lire `AGENTS.md`, le `README.md` et le `CONTRIBUTING.md` avant d'éditer du code.
- Les commits doivent être signés.
- Faire les changements les plus petits possibles qui répondent à la demande. - Faire les changements les plus petits possibles qui répondent à la demande.
- Ne pas pousser, merger ni publier sans demande explicite de l'utilisateur. - Ne pas pousser, fusionner ni publier sans demande explicite de l'utilisateur.
- Suivre les cartes du tableau Kanban du projet pour l'organisation du travail. - Suivre les cartes du tableau Kanban lorsqu'il existe pour organiser le travail.
- En cas de doute, demander plutôt que deviner. - En cas de doute, demander plutôt que de deviner.
+58
View File
@@ -7,6 +7,32 @@ The project follows [Semantic Versioning](https://semver.org/).
## [Unreleased] ## [Unreleased]
### Features ### Features
- **rules:** _(feat)_ write the rules from the dashboard and republish them ([31c0fc8])
- **moderation:** _(feat)_ add the unmute and unban commands ([9f8ac0d])
- **web:** _(feat)_ publish a public status page at /status ([a1e1de7])
- **web:** _(feat)_ search the whole panel from one place ([9acb523])
- **projects:** _(feat)_ gather the cards one member carries ([fcc82d8])
- **projects:** _(feat)_ pull Gitea issues onto any board ([1c21f6f])
- **wiki:** _(feat)_ serve the legal pages at /terms-of-service and /privacy-policy ([3d0e21d])
- **projects:** _(feat)_ add the board interface ([e1b9a5c])
- **projects:** _(feat)_ add a Kanban board per repository and one for the organization ([901ca56])
- **web:** _(feat)_ open a repository from anywhere on its row ([95b51ab])
- **wiki:** _(feat)_ add the reading site and its editor ([e5b7303])
- **wiki:** _(feat)_ serve a public documentation written from the panel ([c76c0b9])
- **web:** _(feat)_ publish the slash commands from the panel ([2622744])
- **voice:** _(feat)_ take back the generated channels the database forgot ([b42fb10])
- **settings:** _(feat)_ make the server settings real, and widen them ([406b5af])
- **web:** _(feat)_ make deploying reachable from where it is looked for ([d439b1b])
- **web:** _(feat)_ refresh the pages as the events arrive ([5481e79])
- **web:** _(feat)_ push live updates to the dashboard ([df89cc5])
- **web:** _(feat)_ serve the dashboard and its interface ([06a9be0])
- **web:** _(feat)_ expose the dashboard API ([bf92bad])
- **web:** _(feat)_ run and record release deployments ([611129b])
- **web:** _(feat)_ read, validate and write the .env configuration ([efaaca3])
- **web:** _(feat)_ add the HTTP layer and Discord-backed sessions ([e03b184])
- **database:** _(feat)_ store dashboard sessions, deploy targets and deployments ([5abe713])
- **gitea:** _(feat)_ add an organization and repository administration client ([4b0737a])
- **config:** _(feat)_ declare the web dashboard environment variables ([e4534d4])
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a]) - **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269]) - **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea]) - **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
@@ -66,7 +92,39 @@ The project follows [Semantic Versioning](https://semver.org/).
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe]) - **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
- **config:** _(feat)_ load and expose environment settings ([d1388b6]) - **config:** _(feat)_ load and expose environment settings ([d1388b6])
### Bug Fixes
- **rules:** _(fix)_ show the rules field with a save button and edit the message ([e6ce594])
- **moderation:** _(fix)_ tell a mute apart from a kick in the logs ([99e1fd2])
- **wiki:** _(fix)_ render the public pages on the server ([8869c74])
- **web:** _(fix)_ stop caching the interface modules ([3f4a570])
- **web:** _(fix)_ keep the stack when a view fails ([c031b4d])
- **web:** _(fix)_ read the interface build date instead of freezing it at startup ([92c27ae])
- **web:** _(fix)_ stop the settings page breaking on an unexpected payload ([75d1e53])
- **web:** _(fix)_ give static assets a validator caches can check ([539b150])
- **web:** _(fix)_ say when the dashboard is disabled ([3bd290c])
- **web:** _(fix)_ say out loud when the dashboard cannot listen ([afcd0e5])
- **config:** _(fix)_ warn when a public address is announced but only loopback is bound ([40032ec])
- **web:** _(fix)_ make the whole repository card open the repository ([e397abc])
- **web:** _(fix)_ pin the sidebar highlight to the route, and name the build ([a44ff0c])
- **web:** _(fix)_ always offer the bootstrap token on the sign-in page ([9c6297e])
- **web:** _(fix)_ let a deploy target be created without a reachable Gitea ([ff15dfe])
- **web:** _(fix)_ keep the sidebar in step with the page being shown ([a0428e0])
- **web:** _(fix)_ derive the OAuth2 redirect from the address actually used ([20ff701])
- **notifications:** _(fix)_ apply the channel overrides set from Discord ([92405ac])
### Other changes ### Other changes
- **agents:** _(docs)_ update the repository conventions and commit rules ([44e990d])
- **web:** _(docs)_ document my tasks, the search and the status page ([566af4d])
- **web:** _(refactor)_ extract the build marker into its own module ([d2256e2])
- **ops:** _(docs)_ correct the deployment path for a panel without a shell ([e3ce266])
- **ops:** _(docs)_ document deployment, CI, monitoring and backups ([1643fcb])
- **web:** _(test)_ lock the sidebar highlighting behind tests ([b793298])
- **web:** _(docs)_ document the wiki, the settings and the command publishing ([5660235])
- **web:** _(style)_ adopt the official FWS mark and its palette ([621f3e4])
- **web:** _(docs)_ document the live updates ([2083133])
- **web:** _(docs)_ document the dashboard and the configuration wizard ([e63d6aa])
- **web:** _(test)_ cover the router, configuration, auth, deployments and server ([bd7fdea])
- **all:** _(refactor)_ uniformisation ([50665c8])
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb]) - **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41]) - **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2]) - **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
+9 -1
View File
@@ -126,7 +126,8 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
| Variable | Usage | | Variable | Usage |
| -------------------------------- | --------------------------------------------------------------------------- | | -------------------------------- | --------------------------------------------------------------------------- |
| `CHANNEL_WELCOME_ID` | Welcome messages | | `CHANNEL_WELCOME_ID` | Welcome messages |
| `CHANNEL_RULES_ID` | Rules (link sent to newcomers) | | `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
| | Later saves edit that same message |
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements | | `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
| `CHANNEL_LOGS_ID` | Functional logs | | `CHANNEL_LOGS_ID` | Functional logs |
| `CHANNEL_MOD_LOGS_ID` | Moderation logs | | `CHANNEL_MOD_LOGS_ID` | Moderation logs |
@@ -289,6 +290,8 @@ Every command checks the FWS level **and** the matching Discord permission. The
| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ | | ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ |
| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action | | `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action |
| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification | | `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification |
| `/unmute` | `user`, `reason` | Moderate Members | ✅ | Lifts the timeout early (clear message when nobody is muted) |
| `/unban` | `user`, `reason` | Ban Members | ✅ | Lifts the ban, even if the member already left, and DMs them |
| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action | | `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action |
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge | | `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge |
| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) | | `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) |
@@ -322,6 +325,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, rules, 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.
@@ -529,6 +536,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h
- FWS documentation: `[link to add]` - FWS documentation: `[link to add]`
- Technical documentation: [`docs/architecture.md`](docs/architecture.md) - Technical documentation: [`docs/architecture.md`](docs/architecture.md)
- Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md) - Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md)
- Operations (deployment, continuous integration, monitoring, backups): [`docs/exploitation.md`](docs/exploitation.md)
- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md) - Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md)
- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_ - Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md) - Instructions for AI agents: [`AGENTS.md`](AGENTS.md)
+8 -1
View File
@@ -128,7 +128,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| Variable | Usage | | Variable | Usage |
| --- | --- | | --- | --- |
| `CHANNEL_WELCOME_ID` | Messages de bienvenue | | `CHANNEL_WELCOME_ID` | Messages de bienvenue |
| `CHANNEL_RULES_ID` | Règlement (lien envoyé aux nouveaux) | | `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS | | `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
| `CHANNEL_LOGS_ID` | Logs fonctionnels | | `CHANNEL_LOGS_ID` | Logs fonctionnels |
| `CHANNEL_MOD_LOGS_ID` | Logs de modération | | `CHANNEL_MOD_LOGS_ID` | Logs de modération |
@@ -291,6 +291,8 @@ Chaque commande vérifie le niveau FWS **et** la permission Discord correspondan
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action | | `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action |
| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP | | `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP |
| `/unmute` | `user`, `reason` | Modérer les membres | ✅ | Lève le timeout avant l’échéance (message clair si la personne n’est pas en exclusion) |
| `/unban` | `user`, `reason` | Bannir | ✅ | Lève le bannissement, même si la personne a déjà quitté, et la prévient en MP |
| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action | | `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action |
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages | | `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages |
| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) | | `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) |
@@ -324,6 +326,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, règlement, 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.
@@ -534,6 +540,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de
- Documentation FWS : `[lien à ajouter]` - Documentation FWS : `[lien à ajouter]`
- Documentation technique : [`docs/architecture.md`](docs/architecture.md) - Documentation technique : [`docs/architecture.md`](docs/architecture.md)
- Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md) - Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md)
- Exploitation (déploiement, intégration continue, surveillance, sauvegardes) : [`docs/exploitation.md`](docs/exploitation.md)
- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) - Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md)
- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)* - Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)*
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md) - Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md)
+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
+305
View File
@@ -0,0 +1,305 @@
# Exploitation
Comment déployer, vérifier, surveiller et sauvegarder FWS-Bot en production. Écrit pour un hébergement de type panel (Pterodactyl), qui est le cas actuel.
Les quatre chapitres sont indépendants et classés par valeur décroissante.
---
## 1. Déployer sans archive
**Le problème qu'on résout.** Téléverser un zip laisse régulièrement une copie partielle : le front plus ancien que l'API, un module oublié, une page qui plante sans raison apparente. Trois symptômes pour une seule cause, et aucun moyen simple de savoir laquelle.
Un déploiement reproductible supprime toute la famille.
> **L'onglet « Console » de Pterodactyl n'est pas un terminal** : c'est l'entrée/sortie du processus en cours. On n'y lance pas de commande shell, même avec tous les droits du panel. Si tu disposes d'un vrai shell ailleurs, suis le point 1.0 ; sinon, tout se fait depuis le tableau de bord, à partir du point 1.1.
### 1.0 Si tu as un accès shell
Assure-toi d'abord d'être **sur le bon système de fichiers** — celui que le bot lit. Un `git pull` au mauvais endroit ne produit aucune erreur et ne change rien, ce qui est le plus trompeur des résultats :
```bash
cd /home/container
ls package.json src/index.js .env && echo "bon endroit"
```
Si cette commande échoue, ton shell ne voit pas le conteneur du bot : passe au point 1.1.
Sinon, l'amorçage se fait directement :
```bash
cp .env .env.sauvegarde && tar czf data-sauvegarde.tgz data/
git init
git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git
git fetch origin main
git reset --hard origin/main
npm ci --omit=dev
```
Puis saute au point 1.3 pour déclarer la cible de production, qui te permettra de déployer d'un clic depuis le tableau de bord plutôt que de revenir ici à chaque fois.
> ⚠️ Ne lance **jamais** `git clean -fd` dans ce dossier : il effacerait `.env` et la base.
### 1.1 Autoriser l'exécution de commandes
**Tableau de bord → Configuration .env → Tableau de bord web** (niveau Owner) :
| Variable | Valeur |
| --------------------------- | ------ |
| `WEB_ALLOW_COMMAND_DEPLOYS` | `true` |
| `WEB_ALLOW_RESTART` | `true` |
Enregistre, puis redémarre le bot depuis le panel. Ces deux valeurs ne sont lues qu'au démarrage.
> Elles permettent d'exécuter une commande sur la machine du bot depuis un navigateur — une exécution de code arbitraire. Réservées au niveau Owner, désactivées par défaut. N'ouvre l'accès Owner qu'à des personnes de confiance.
### 1.2 Amorcer le clone sans shell
Si le point 1.0 ne s'applique pas : le dossier du conteneur contient aujourd'hui une archive décompressée, pas un dépôt. On le convertit avec une cible jetable, exécutée par le bot lui-même.
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| --------------------- | -------------------------------- |
| Nom | `amorçage` |
| Dépôt | `FWS/fws-discordbot` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | voir ci-dessous |
```bash
git init && git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git && git fetch origin main && git reset --hard origin/main
```
Clique **Déployer**, puis lis le journal dans l'historique. Deux cas d'échec :
- **`git: not found`** — l'image du conteneur n'a pas git. Utilise la variante sans git du point 1.5.
- **authentification refusée** — le dépôt est privé. Remplace l'URL par `https://<utilisateur>:<jeton>@gitea.nocode-var.tech/FWS/fws-discordbot.git`. Le jeton est alors stocké dans la configuration de la cible, en base : utilise un jeton dédié, en lecture seule.
`git reset --hard` écrase les fichiers **suivis**. Ton `.env` et ton dossier `data/` sont ignorés par git, donc intacts.
> ⚠️ N'ajoute **jamais** `git clean -fd` à cette commande : elle effacerait `.env` et la base.
Supprime ensuite la cible `amorçage` : elle ne sert qu'une fois.
### 1.3 Déclarer la cible de production
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| ----------------------- | ---------------------------------------------------------------------------- |
| Nom | `production` |
| Dépôt | `FWS/fws-discordbot` |
| Environnement | `production` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | `git fetch origin main && git reset --hard origin/main && npm ci --omit=dev` |
| Déploiement automatique | à activer si tu veux qu'une release publiée déploie seule |
### 1.4 Le cycle courant
1. **Déploiements → Déployer** sur `production`. Le journal complet est conservé, réussite comme échec.
2. **Paramètres → Redémarrer le bot** — le code n'est relu qu'au démarrage.
Contrôle, depuis n'importe où :
```bash
curl -s http://node01.zi-host.ch:25571/api/health
```
`buildAt` doit refléter ton dernier commit. C'est le seul indicateur fiable de ce qui tourne réellement.
### 1.5 Si le conteneur n'a pas git
Gitea sert une archive de n'importe quelle branche. La commande devient :
```bash
curl -sL -H "Authorization: token TON_JETON" https://gitea.nocode-var.tech/api/v1/repos/FWS/fws-discordbot/archive/main.tar.gz | tar xz --strip-components=1 && npm ci --omit=dev
```
Moins bien que git — pas d'historique, pas de moyen de savoir ce qui a changé — mais reproductible, et suffisant pour supprimer le téléversement à la main.
### Ce qu'il faut savoir
- `npm ci --omit=dev` n'installe ni ESLint, ni Prettier, ni de quoi lancer les tests. C'est voulu : ils tournent en intégration continue (chapitre 2), pas en production.
- Si ton egg Pterodactyl réinstalle les fichiers au démarrage, il écrasera le clone. Vérifie l'option _Auto-update / Reinstall on boot_ et désactive-la.
- Les migrations de base s'appliquent toutes seules au démarrage : rien à lancer.
- Tout ce chapitre reste faisable en **SFTP** si tu préfères : le panel en donne les identifiants, et un client comme FileZilla remplace le téléversement par zip. Mais tu restes exposé à la copie partielle, que le déploiement par commande supprime.
---
## 2. Faire tourner les tests avant de déployer
**Le problème qu'on résout.** 301 tests et un lint existent, et ne tournent jamais avant une mise en production. Un déplacement de cartes cassé est passé inaperçu jusqu'à ce qu'un test l'attrape — après coup.
Le fichier de workflow est déjà dans le dépôt : [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml). Il reste à donner un exécuteur à Gitea.
### 2.1 Activer Actions sur l'instance
Côté administration Gitea, dans `app.ini` :
```ini
[actions]
ENABLED = true
```
Puis redémarrer Gitea. Si l'instance ne t'appartient pas, c'est à demander à son administration.
### 2.2 Enregistrer un exécuteur
**Dépôt → Settings → Actions → Runners → Create new runner** te donne un jeton d'enregistrement.
Sur une machine qui a Docker et qui joint ton Gitea — ton poste, un VPS, ou le nœud lui-même :
```bash
curl -sL -o act_runner \
https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64
chmod +x act_runner
./act_runner register --no-interactive \
--instance https://gitea.nocode-var.tech \
--token <JETON_DENREGISTREMENT> \
--name fws-runner \
--labels ubuntu-latest:docker://node:22-bookworm
./act_runner daemon
```
Sans Docker, remplace l'étiquette par `ubuntu-latest:host` — les tâches s'exécutent alors directement sur la machine, qui doit avoir Node 22.
Pour qu'il survive à un redémarrage, place-le en service systemd ou en conteneur `--restart=always`.
### 2.3 Vérifier
Pousse une branche : l'onglet **Actions** du dépôt montre le résultat, et la pull request affiche son état.
### Pourquoi `format:check` n'est pas dans le workflow
Le dépôt contient encore des fichiers en CRLF antérieurs à la configuration Prettier. L'étape échouerait sur du code que personne n'a touché.
Pour l'ajouter : normalise les fins de ligne dans un commit dédié (`refactor(all): normalise les fins de ligne`), puis ajoute l'étape. Tant que ce n'est pas fait, l'absence est volontaire.
---
## 3. Savoir que le bot est tombé
**Le problème qu'on résout.** Une soirée passée à chercher pourquoi le site ne répondait plus, alors qu'une sonde aurait répondu en trente secondes.
Le bot expose déjà tout ce qu'il faut :
```json
GET /api/health
{ "status": "ok", "version": "0.1.0", "buildAt": "…", "uptimeMs": 106470 }
```
### 3.1 Surveiller depuis l'extérieur
Un bot ne peut pas signaler sa propre mort : il faut une sonde **externe**. [Uptime Kuma](https://github.com/louislam/uptime-kuma) est léger et sait écrire sur Discord.
```bash
docker run -d --restart=always -p 3001:3001 \
-v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
```
Puis, dans son interface :
| Réglage | Valeur |
| ------------ | ------------------------------------------- |
| Type | HTTP(s) - Keyword |
| URL | `http://node01.zi-host.ch:25571/api/health` |
| Mot-clé | `"status":"ok"` |
| Intervalle | 60 s |
| Notification | Webhook Discord vers ton salon de logs |
> **Surveille l'origine, pas le domaine public.** Cloudflare renvoie un challenge à toute requête non-navigateur : une sonde sur `https://fws-bot.laxacube.ch` signalerait une panne permanente qui n'existe pas.
Le mot-clé compte : une page qui répond `200` mais sans `"status":"ok"` n'est pas un bot en bonne santé.
### 3.2 Une page que les autres peuvent lire
`/status` répond sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue côté serveur, sans JavaScript, et se rafraîchit toute seule.
C’est l’adresse à donner à la communauté quand quelqu’un demande « c’est en panne ou c’est moi ? ».
`/api/status` en donne la version JSON. Elle vaut mieux que `/api/health` pour une sonde qui affiche un tableau de bord :
```json
GET /api/status
{ "bot": { "online": true, "pingMs": 42, "version": "0.1.0" },
"environments": [ { "environment": "production", "status": "success", "tone": "ok" } ],
"releases": [ … ] }
```
`WEB_PUBLIC_STATUS=false` désactive les deux. Un dépôt privé n’apparaît jamais par son nom sur la page publique.
### 3.3 Ce que le bot surveille déjà lui-même
- Chaque déploiement, réussi ou non, est annoncé sur Discord et consigné avec son journal.
- Les erreurs d'appel Gitea partent dans le salon `errors`.
- **Paramètres → Tester la connexion** vérifie Discord et Gitea à la demande.
Ça couvre les pannes partielles. Ça ne couvre pas un processus mort — d'où le point 3.1.
---
## 4. Sauvegarder hors du conteneur
**Le problème qu'on résout.** Le bouton _Sauvegarder la base_ écrit dans `data/backups`, **à l'intérieur du conteneur**. Une reconstruction efface les deux. C'est déjà arrivé : les salons vocaux orphelins venaient d'une base repartie de zéro.
### 4.1 Sauvegardes du panel (le plus simple)
Pterodactyl sait archiver le serveur entier, hors conteneur.
**Panel → Schedules → Create schedule**
| Réglage | Valeur |
| ------- | ----------------------- |
| Nom | Sauvegarde hebdomadaire |
| Cron | `0 4 * * 1` (lundi 4 h) |
| Tâche | _Create backup_ |
Les archives apparaissent dans l'onglet **Backups**, avec téléchargement. Vérifie la limite d'archives de ton offre.
### 4.2 Instantané cohérent de la base
Une archive de fichiers peut attraper la base en cours d'écriture. Le bot, lui, produit une copie cohérente (`VACUUM INTO`), même journal WAL actif.
Crée un jeton dans **Paramètres → Jetons d'API** (niveau Owner), puis, depuis une machine qui tourne en permanence :
```bash
# Chaque nuit à 3 h
0 3 * * * curl -sS -X POST -H "Authorization: Bearer fws_…" \
http://node01.zi-host.ch:25571/api/settings/backup
```
Le fichier atterrit dans `BACKUP_DIR`, que la sauvegarde du panel emporte ensuite.
### 4.3 Vraiment hors site
Une sauvegarde chez le même hébergeur ne protège pas d'un incident chez lui. Depuis une machine qui a l'accès SFTP du panel :
```bash
rclone sync sftp-panel:/home/container/data backblaze:fws-bot-backups \
--backup-dir backblaze:fws-bot-backups/anciens/$(date +%F)
```
### 4.4 Tester la restauration
Une sauvegarde jamais restaurée n'est pas une sauvegarde. Une fois :
```bash
cp fws-bot-2026-09-24.sqlite /tmp/test.sqlite
DATABASE_PATH=/tmp/test.sqlite npm run db:init
```
La commande doit se terminer sans erreur et appliquer les migrations.
---
## Dans quel ordre
1. **Chapitre 1** — supprime une famille entière de pannes, ne demande que de la configuration.
2. **Chapitre 2** — évite de découvrir un bug en production.
3. **Chapitre 4** — protège ce qui n'est pas remplaçable.
4. **Chapitre 3** — utile, mais vient après ce qui empêche les pannes plutôt que ce qui les signale.
+88 -7
View File
@@ -54,6 +54,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
| Page | Contenu | | Page | Contenu |
| ---------------------- | ----------------------------------------------------------------------------------------------- | | ---------------------- | ----------------------------------------------------------------------------------------------- |
| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements | | **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements |
| **Mes tâches** | Les cartes qui te sont assignées, tous tableaux confondus, la plus urgente en premier |
| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt | | **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt |
| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages | | **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages |
| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés | | **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés |
@@ -61,7 +62,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes | | **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot | | **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués | | **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
| **Paramètres** | Comportement du bot, connexions, sessions, jetons d'API, maintenance | | **Paramètres** | Comportement du bot, règlement, connexions, sessions, jetons d'API, maintenance |
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré | | **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
## 4. Assistant de configuration ## 4. Assistant de configuration
@@ -142,7 +143,82 @@ 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. Trouver et suivre son travail
### Mes tâches
**Tableau de bord → Mes tâches** rassemble les cartes qui te sont assignées sur **tous** les tableaux, groupées par échéance : en retard, pour aujourd’hui, cette semaine, plus tard, sans date. Les cartes terminées sont repliées en bas.
- Le bouton rond à gauche d’une carte la déplace dans la colonne « terminé » de son tableau, sans quitter la page.
- Le compteur de la barre latérale indique le nombre de cartes ouvertes, en rouge dès qu’une est en retard.
- Le sélecteur en haut à droite permet de regarder la charge d’un autre membre, quand plusieurs personnes portent des cartes.
Une carte n’apparaît ici que si elle a un **assigné**. C’est le seul champ qui compte pour cette page.
### Recherche globale
**⌘K** (ou **Ctrl+K**, ou la barre « Rechercher ») ouvre une recherche unique sur :
| Source | Où elle mène | D’où elle vient |
| ----------- | -------------------------------------- | ------------------------- |
| Pages | L’onglet correspondant | Le navigateur, sans appel |
| Cartes | Le tableau qui la porte | La base locale |
| Dépôts | La fiche du dépôt | Gitea, en cache 60 s |
| Issues / PR | Gitea, dans un onglet | Gitea |
| Wiki | La page publique | La base locale |
| Membres | L’onglet Discord, recherche préremplie | Le cache du bot |
Les pages sont filtrées dans le navigateur : la palette répond avant même d’avoir interrogé le serveur, et reste utile si Gitea ne répond pas. Une source qui échoue est simplement absente des résultats.
Les flèches naviguent, **Entrée** ouvre, **Échap** ferme. Une page à laquelle tu n’as pas accès n’apparaît jamais dans les résultats.
### Page de statut publique
**`/status`** est lisible sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue **côté serveur, sans une seule ligne de JavaScript**, et s’actualise par une balise `meta refresh` — une page de statut qui a besoin d’un navigateur moderne pour dire qu’il y a une panne est une page inutile au moment où elle sert.
Deux garde-fous, parce que la page est publique :
- Un dépôt que Gitea ne liste pas comme public apparaît **sans son nom** : l’environnement reste visible, le dépôt non.
- La bannière annonce toujours le pire état vrai. Un déploiement en échec empêche l’en-tête vert, même si le bot répond.
`WEB_PUBLIC_STATUS=false` la désactive entièrement ; `/status` renvoie alors 404, comme `/api/status`.
`/api/status` donne la même chose en JSON, sans session : c’est ce qu’une sonde de supervision doit interroger, plutôt que `/api/health` qui ne dit que « le processus vit ».
## 8. 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.
## 9. Réglages du serveur
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, règlement, 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`.
### Rédiger et publier le règlement
La section **Règlement** de la page Paramètres écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et **Enregistrer** les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. L'identifiant du message est retenu en base (`rules_messages`) : les enregistrements suivants **modifient ce message**, même lien, même place dans le salon et épingle conservée, au lieu d'empiler les versions. Un message supprimé à la main, un salon devenu inaccessible ou un bot qui ne peut plus éditer font repartir sur un nouveau message ; un épinglage refusé est signalé sans bloquer la publication. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
## 10. 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.
## 11. 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 +228,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é ## 12. 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 +239,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 ## 13. Fonctionnement interne
```text ```text
src/web/ src/web/
@@ -180,12 +256,17 @@ src/web/
├── services/ ├── services/
│ ├── env-schema.js # Description documentée de chaque variable │ ├── env-schema.js # Description documentée de chaque variable
│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env │ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env
│ └── deploy-service.js # Exécution des déploiements et notifications │ ├── deploy-service.js # Exécution des déploiements et notifications
│ ├── build-info.js # Version et date de l’interface réellement servie
│ ├── wiki-seed.js # Pages créées au premier démarrage, adresses publiques
│ ├── wiki-render.js # Wiki rendu côté serveur
│ ├── status-service.js # Instantané public : bot, déploiements, releases
│ └── status-render.js # Page /status rendue côté serveur, sans script
└── public/ # Front servi tel quel (aucun build) └── public/ # Front servi tel quel (aucun build)
├── index.html ├── index.html
├── styles.css ├── styles.css
├── app.js # Shell, navigation, routage par fragment ├── app.js # Shell, navigation, routage par fragment
├── core/ # dom.js, api.js, ui.js ├── core/ # dom.js, api.js, ui.js, live.js, nav.js, palette.js
└── views/ # Une vue par page └── views/ # Une vue par page
``` ```
@@ -207,7 +288,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 ## 14. 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 });
+3 -4
View File
@@ -1,7 +1,7 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { listActions } from '../../database/repositories/moderation-repository.js'; import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration } from '../../services/moderation/moderation-service.js'; import { formatDuration, moderationLabel } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js'; import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -20,11 +20,10 @@ export const data = new SlashCommandBuilder()
); );
function formatEntry(row) { function formatEntry(row) {
const meta = MODERATION_ACTIONS[row.action];
const target = row.target_id ? `<@${row.target_id}>` : 'salon'; const target = row.target_id ? `<@${row.target_id}>` : 'salon';
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : ''; const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
return ( return (
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` + `\`${row.created_at}\` **${moderationLabel(row.action)}** — ${target}${duration}\n` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}` `↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
); );
} }
+10 -9
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;
@@ -37,7 +40,7 @@ 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.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`); await target.timeout(durationMs, reason ?? `Mise en sourdine de ${minutes} minutes`);
await logModerationAction(interaction, { await logModerationAction(interaction, {
action: 'mute', action: 'mute',
@@ -45,16 +48,14 @@ 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: [
successEmbed( successEmbed(
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`, `C’est fait : **${target.user.tag}** est en sourdine pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
), ),
], ],
}); });
+62
View File
@@ -0,0 +1,62 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
assertModerationTarget,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('unban')
.setDescription('Lever le bannissement d’un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Counterpart of `/ban`, usable whether or not the member already left. */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
// Fetching the ban first turns “not banned” into a clear message instead of
// the missing-ban error Discord returns from the removal itself.
const ban = await interaction.guild.bans.fetch(user.id).catch(() => null);
if (!ban) {
throw new UserFacingError(`${user.tag} n’est pas banni de ce serveur : il n’y a rien à lever.`);
}
// A banned member has usually already left, so the hierarchy is only checked
// while they are still on the server (a ban applied too quickly, typically).
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) assertModerationTarget(interaction, member);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.remove(
user.id,
reason ?? `Débannissement demandé par ${interaction.user.tag}`,
);
await logModerationAction(interaction, { action: 'unban', targetId: user.id, reason });
// A direct message is the only way to tell someone they may come back.
const recipient = member ?? (await interaction.client.users.fetch(user.id).catch(() => null));
if (recipient) {
await notifyTarget(
recipient,
{ embeds: [targetNoticeEmbed({ action: 'unban', guildName: interaction.guild.name, reason })] },
interaction.guildId,
);
}
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${user.tag}** peut de nouveau rejoindre le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+52
View File
@@ -0,0 +1,52 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
notifyTarget,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('unmute')
.setDescription('Lever l’exclusion temporaire d’un membre avant la fin')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Counterpart of `/mute`: clears the timeout early and keeps the trail. */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
// Discord answers a timeout removal on a member who is not muted with an
// opaque error, so the check turns it into an explicit message.
if (!target.isCommunicationDisabled()) {
throw new UserFacingError(
`${target.user.tag} n’est pas en exclusion temporaire : cette personne peut déjà écrire.`,
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(null, reason ?? `Levée d’exclusion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'unmute', targetId: target.id, reason });
await notifyTarget(target, {
embeds: [targetNoticeEmbed({ action: 'unmute', guildName: interaction.guild.name, reason })],
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** peut de nouveau écrire sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+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: [
+19 -7
View File
@@ -28,14 +28,26 @@ export const ACCESS_LABELS = Object.freeze({
[ACCESS_LEVELS.OWNER]: 'Owner', [ACCESS_LEVELS.OWNER]: 'Owner',
}); });
/** Moderation actions: Discord label, embed color and stored duration (M8). */ /**
* Moderation actions: Discord label, embed color and stored duration (M8).
* The emoji belongs to the entry so every surface (log channel, direct message,
* `/mod logs`, dashboard) tells a mute from a kick at a glance: the wording
* alone read like a temporary kick.
*/
export const MODERATION_ACTIONS = Object.freeze({ export const MODERATION_ACTIONS = Object.freeze({
warn: { label: 'Avertissement', color: COLORS.warning, duration: false }, warn: { label: 'Avertissement', emoji: '⚠️', color: COLORS.warning, duration: false },
mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true }, mute: { label: 'Mise en sourdine', emoji: '🔇', color: COLORS.moderation, duration: true },
kick: { label: 'Expulsion', color: COLORS.moderation, duration: false }, unmute: {
ban: { label: 'Bannissement', color: COLORS.error, duration: false }, label: 'Levée de la mise en sourdine',
clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false }, emoji: '🔊',
role: { label: 'Modification de rôle', color: COLORS.primary, duration: false }, color: COLORS.success,
duration: false,
},
kick: { label: 'Expulsion', emoji: '👢', color: COLORS.moderation, duration: false },
ban: { label: 'Bannissement', emoji: '🔨', color: COLORS.error, duration: false },
unban: { label: 'Débannissement', emoji: '🔓', color: COLORS.success, duration: false },
clear: { label: 'Supclusion de messages', emoji: '🧹', color: COLORS.warning, duration: false },
role: { label: 'Modification de rôle', emoji: '🏷️', color: COLORS.primary, duration: false },
}); });
/** Ticket categories and who can see them (M0-T05 / M6-T01). */ /** Ticket categories and who can see them (M0-T05 / M6-T01). */
+3
View File
@@ -92,6 +92,9 @@ export const env = Object.freeze({
// dashboard, so it stays off until it is explicitly enabled (M16-T06). // dashboard, so it stays off until it is explicitly enabled (M16-T06).
allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'), allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
allowRestart: readBool('WEB_ALLOW_RESTART'), allowRestart: readBool('WEB_ALLOW_RESTART'),
// The public status page is opt-out rather than opt-in: a bot people rely on
// owes them a place to check before asking.
publicStatus: readBool('WEB_PUBLIC_STATUS', true),
deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000), deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240), rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
}, },
+266
View File
@@ -0,0 +1,266 @@
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: 'rules',
title: 'Règlement',
summary: 'Message affiché et épinglé dans le salon des règles.',
},
{ 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 de mise en sourdine 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,
},
// --- Règlement ---------------------------------------------------------------
{
key: 'rules.markdown',
section: 'rules',
label: 'Règlement (markdown)',
help: 'Enregistré et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Enregistrer modifie le message déjà publié.',
type: 'markdown',
default: '',
maxLength: 4000,
},
// --- 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);
+57
View File
@@ -0,0 +1,57 @@
-- Kanban boards: one per repository, plus one for the organization (M18)
CREATE TABLE IF NOT EXISTS project_boards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
-- 'org' has no repository; 'repo' carries `owner/name`.
scope TEXT NOT NULL CHECK (scope IN ('org', 'repo')),
repository TEXT,
name TEXT NOT NULL,
description TEXT,
archived INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- One board per repository, and a single organization board per guild.
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_repository
ON project_boards (guild_id, repository) WHERE repository IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_org
ON project_boards (guild_id) WHERE scope = 'org';
CREATE TABLE IF NOT EXISTS project_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
name TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
-- 0 means no limit; above it the column is flagged as overloaded.
wip_limit INTEGER NOT NULL DEFAULT 0,
-- Cards dropped here are considered finished, which drives the board counters.
is_done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_columns_board ON project_columns (board_id, position);
CREATE TABLE IF NOT EXISTS project_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
column_id INTEGER NOT NULL REFERENCES project_columns (id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT,
position INTEGER NOT NULL DEFAULT 0,
-- Discord id of whoever carries the card.
assignee_id TEXT,
-- `owner/repo#12`, resolved against Gitea when the forge answers.
issue_ref TEXT,
labels TEXT NOT NULL DEFAULT '[]',
due_at TEXT,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_cards_column ON project_cards (column_id, position);
CREATE INDEX IF NOT EXISTS idx_cards_board ON project_cards (board_id);
CREATE INDEX IF NOT EXISTS idx_cards_assignee ON project_cards (board_id, assignee_id);
@@ -0,0 +1,9 @@
-- The legal pages move to the addresses platforms expect (M17)
--
-- Discord, and most app stores, ask for a terms URL and a privacy URL. Serving
-- them under `/wiki/` works but reads badly in a form field, so they move to
-- the root. Renaming rather than recreating keeps whatever the organization
-- has already written in them.
UPDATE wiki_pages SET slug = 'terms-of-service' WHERE slug = 'conditions-utilisation';
UPDATE wiki_pages SET slug = 'privacy-policy' WHERE slug = 'politique-confidentialite';
@@ -0,0 +1,23 @@
-- Lifted sanctions join the sanctions in the moderation history
--
-- `/unmute` and `/unban` are recorded like `/mute` and `/ban`, but SQLite cannot
-- alter a CHECK constraint: the table is rebuilt and the rows copied over so the
-- history already stored survives the migration.
CREATE TABLE moderation_actions_lifted (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'unmute', 'kick', 'ban', 'unban', 'clear', 'role')),
target_id TEXT,
moderator_id TEXT NOT NULL,
reason TEXT,
duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
INSERT INTO moderation_actions_lifted (id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at)
SELECT id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at FROM moderation_actions;
DROP TABLE moderation_actions;
ALTER TABLE moderation_actions_lifted RENAME TO moderation_actions;
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
@@ -0,0 +1,13 @@
-- The rules message published from the dashboard (M19)
--
-- The bot republishes the rules by deleting the previous message and sending
-- the new one, so it has to remember which message it owns. Without this the
-- channel would slowly fill with outdated copies.
CREATE TABLE IF NOT EXISTS rules_messages (
guild_id TEXT PRIMARY KEY,
channel_id TEXT NOT NULL,
message_id TEXT NOT NULL,
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@@ -0,0 +1,352 @@
import { getDatabase } from '../index.js';
/** Kanban boards, their columns and their cards (M18). */
/** Same wording as the board described in the FWS README. */
export const DEFAULT_COLUMNS = Object.freeze([
{ name: 'À faire', wipLimit: 0, isDone: false },
{ name: 'En cours', wipLimit: 3, isDone: false },
{ name: 'En revue', wipLimit: 0, isDone: false },
{ name: 'Terminé', wipLimit: 0, isDone: true },
]);
const parseBoard = (row) => (row ? { ...row, archived: Boolean(row.archived) } : null);
const parseColumn = (row) => (row ? { ...row, is_done: Boolean(row.is_done) } : null);
const parseCard = (row) => (row ? { ...row, labels: JSON.parse(row.labels || '[]') } : null);
// --- Boards ------------------------------------------------------------------
export function createBoard({
guildId,
scope,
repository = null,
name,
description = null,
createdBy = null,
}) {
const database = getDatabase();
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_boards (guild_id, scope, repository, name, description, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, scope, repository, name, description, createdBy);
const id = Number(lastInsertRowid);
// A board with no column cannot receive a card, so it is never created empty.
for (const [index, column] of DEFAULT_COLUMNS.entries()) {
addColumn({
boardId: id,
name: column.name,
position: index,
wipLimit: column.wipLimit,
isDone: column.isDone,
});
}
return getBoard(id);
}
export function getBoard(id) {
return parseBoard(getDatabase().prepare('SELECT * FROM project_boards WHERE id = ?').get(id) ?? null);
}
export function getBoardByRepository(guildId, repository) {
return parseBoard(
getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? AND repository = ?')
.get(guildId, repository) ?? null,
);
}
export function getOrgBoard(guildId) {
return parseBoard(
getDatabase().prepare("SELECT * FROM project_boards WHERE guild_id = ? AND scope = 'org'").get(guildId) ??
null,
);
}
export function listBoards(guildId) {
return getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? ORDER BY scope DESC, name')
.all(guildId)
.map(parseBoard);
}
export function updateBoard(id, { name, description, archived }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (description !== undefined) (fields.push('description = ?'), values.push(description));
if (archived !== undefined) (fields.push('archived = ?'), values.push(archived ? 1 : 0));
if (fields.length === 0) return getBoard(id);
getDatabase()
.prepare(`UPDATE project_boards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getBoard(id);
}
export function removeBoard(id) {
return getDatabase().prepare('DELETE FROM project_boards WHERE id = ?').run(id).changes;
}
// --- Columns -----------------------------------------------------------------
export function addColumn({ boardId, name, position = null, wipLimit = 0, isDone = false }) {
const database = getDatabase();
const nextPosition =
position ??
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_columns WHERE board_id = ?')
.get(boardId).next ??
0;
const { lastInsertRowid } = database
.prepare(
'INSERT INTO project_columns (board_id, name, position, wip_limit, is_done) VALUES (?, ?, ?, ?, ?)',
)
.run(boardId, name, nextPosition, wipLimit, isDone ? 1 : 0);
return getColumn(Number(lastInsertRowid));
}
export function getColumn(id) {
return parseColumn(getDatabase().prepare('SELECT * FROM project_columns WHERE id = ?').get(id) ?? null);
}
export function listColumns(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_columns WHERE board_id = ? ORDER BY position, id')
.all(boardId)
.map(parseColumn);
}
export function updateColumn(id, { name, wipLimit, isDone, position }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (wipLimit !== undefined) (fields.push('wip_limit = ?'), values.push(Number(wipLimit) || 0));
if (isDone !== undefined) (fields.push('is_done = ?'), values.push(isDone ? 1 : 0));
if (position !== undefined) (fields.push('position = ?'), values.push(Number(position) || 0));
if (fields.length === 0) return getColumn(id);
getDatabase()
.prepare(`UPDATE project_columns SET ${fields.join(', ')} WHERE id = ?`)
.run(...values, id);
return getColumn(id);
}
export function removeColumn(id) {
return getDatabase().prepare('DELETE FROM project_columns WHERE id = ?').run(id).changes;
}
export function countColumns(boardId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_columns WHERE board_id = ?')
.get(boardId).count;
}
// --- Cards -------------------------------------------------------------------
export function addCard({
boardId,
columnId,
title,
body = null,
assigneeId = null,
issueRef = null,
labels = [],
dueAt = null,
createdBy = null,
}) {
const database = getDatabase();
const next =
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_cards WHERE column_id = ?')
.get(columnId).next ?? 0;
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_cards
(board_id, column_id, title, body, position, assignee_id, issue_ref, labels, due_at, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
boardId,
columnId,
title,
body,
next,
assigneeId,
issueRef,
JSON.stringify(labels),
dueAt,
createdBy,
);
return getCard(Number(lastInsertRowid));
}
export function getCard(id) {
return parseCard(getDatabase().prepare('SELECT * FROM project_cards WHERE id = ?').get(id) ?? null);
}
export function listCards(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_cards WHERE board_id = ? ORDER BY column_id, position, id')
.all(boardId)
.map(parseCard);
}
export function countCardsInColumn(columnId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_cards WHERE column_id = ?')
.get(columnId).count;
}
export function updateCard(id, { title, body, assigneeId, issueRef, labels, dueAt }) {
const fields = [];
const values = [];
if (title !== undefined) (fields.push('title = ?'), values.push(title));
if (body !== undefined) (fields.push('body = ?'), values.push(body));
if (assigneeId !== undefined) (fields.push('assignee_id = ?'), values.push(assigneeId || null));
if (issueRef !== undefined) (fields.push('issue_ref = ?'), values.push(issueRef || null));
if (labels !== undefined) (fields.push('labels = ?'), values.push(JSON.stringify(labels)));
if (dueAt !== undefined) (fields.push('due_at = ?'), values.push(dueAt || null));
if (fields.length === 0) return getCard(id);
getDatabase()
.prepare(`UPDATE project_cards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getCard(id);
}
/**
* Moves a card to a rank in a column.
*
* The order is rebuilt explicitly — take the column without the card, insert it
* at the wanted index, renumber — rather than nudged with fractional positions.
* Within one column the card has to be removed before being counted back in, a
* subtlety fractional ranks get wrong every time.
*/
export function moveCard(id, { columnId, position = 0 }) {
const database = getDatabase();
const card = getCard(id);
if (!card) return null;
const order = (target) =>
database
.prepare('SELECT id FROM project_cards WHERE column_id = ? ORDER BY position, id')
.all(target)
.map((row) => row.id)
.filter((cardId) => cardId !== id);
const write = (ids, target) => {
for (const [index, cardId] of ids.entries()) {
database
.prepare(
"UPDATE project_cards SET column_id = ?, position = ?, updated_at = datetime('now') WHERE id = ?",
)
.run(target, index, cardId);
}
};
const destination = order(columnId);
const rank = Math.max(0, Math.min(Number(position) || 0, destination.length));
destination.splice(rank, 0, id);
database.exec('BEGIN');
try {
// The column it leaves closes its gap, the one it joins makes room.
if (card.column_id !== columnId) write(order(card.column_id), card.column_id);
write(destination, columnId);
database.exec('COMMIT');
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
return getCard(id);
}
export function removeCard(id) {
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
}
const parseAssignedCard = (row) => ({
...parseCard(row),
column_is_done: Boolean(row.column_is_done),
});
/**
* Cards carried by one member, across every board of the guild (M19).
*
* The column travels with the card: « what am I on today » cannot be answered
* without knowing whether a card is still open, and asking per card turns the
* page into a staircase of queries. `done_column_id` comes along for the same
* reason — finishing a card from here is then a single move.
*/
export function listCardsForAssignee(guildId, assigneeId) {
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done,
(SELECT d.id FROM project_columns d
WHERE d.board_id = b.id AND d.is_done = 1
ORDER BY d.position, d.id LIMIT 1) AS done_column_id
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id = ?
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
)
.all(guildId, assigneeId)
.map(parseAssignedCard);
}
/**
* Who carries cards, and how many are still open.
*
* Lets the page offer a picker without asking Discord for the member list,
* which is unavailable whenever the bot is offline — precisely when someone is
* most likely to be looking at the dashboard.
*/
export function listAssignees(guildId) {
return getDatabase()
.prepare(
`SELECT c.assignee_id AS assigneeId,
COUNT(*) AS total,
SUM(CASE WHEN col.is_done = 1 THEN 0 ELSE 1 END) AS open
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id IS NOT NULL AND c.assignee_id <> ''
GROUP BY c.assignee_id
ORDER BY open DESC, total DESC`,
)
.all(guildId);
}
/** Cards whose title, body, labels or issue matches, for the command palette (M19). */
export function searchCards(guildId, term, limit = 8) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ?
AND (c.title LIKE ? OR c.body LIKE ? OR c.labels LIKE ? OR c.issue_ref LIKE ?)
ORDER BY col.is_done, c.due_at IS NULL, c.due_at, c.id DESC
LIMIT ?`,
)
.all(guildId, needle, needle, needle, needle, limit)
.map(parseAssignedCard);
}
@@ -0,0 +1,24 @@
import { getDatabase } from '../index.js';
/** The rules message the bot published, so the next version can replace it. */
export function setRulesMessage({ guildId, channelId, messageId, updatedBy = null }) {
getDatabase()
.prepare(
`INSERT INTO rules_messages (guild_id, channel_id, message_id, updated_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id) DO UPDATE SET
channel_id = excluded.channel_id,
message_id = excluded.message_id,
updated_by = excluded.updated_by,
updated_at = datetime('now')`,
)
.run(guildId, channelId, messageId, updatedBy);
}
export function getRulesMessage(guildId) {
return getDatabase().prepare('SELECT * FROM rules_messages WHERE guild_id = ?').get(guildId) ?? null;
}
export function clearRulesMessage(guildId) {
return getDatabase().prepare('DELETE FROM rules_messages WHERE guild_id = ?').run(guildId).changes;
}
@@ -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);
} }
+9
View File
@@ -27,6 +27,15 @@ await registerEvents(client);
const webServer = env.web.enabled ? startWebServer({ client }) : null; const webServer = env.web.enabled ? startWebServer({ client }) : null;
const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null; const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null;
// Saying nothing when the dashboard is off is how an afternoon gets lost
// looking for a site that was never asked to start.
if (!env.web.enabled) {
logger.warn(
'Le tableau de bord est désactivé : `WEB_ENABLED` ne vaut pas `true`. ' +
'Aucun site ne sera servi. Mets `WEB_ENABLED=true` dans le .env puis redémarre.',
);
}
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason)); process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error)); process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
+9
View File
@@ -40,6 +40,15 @@ export const org = {
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList), giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
createRepo: (payload, owner = defaultOwner()) => createRepo: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }), giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
/**
* Issues and pull requests of the whole organization, in one request.
*
* The per-repository endpoint would mean one call per repository, which the
* command palette cannot afford on every keystroke. Absent before Gitea 1.15,
* so callers tolerate a rejection.
*/
searchIssues: ({ owner = defaultOwner(), q, state = 'open', type, limit = 10 } = {}) =>
giteaRequest(`/repos/issues/search${query({ q, owner, state, type, limit })}`).then(asList),
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */ /** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
whoami: () => giteaRequest('/user'), whoami: () => giteaRequest('/user'),
}; };
+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;
+29 -2
View File
@@ -1,11 +1,23 @@
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';
import { recordAction } from '../../database/repositories/moderation-repository.js'; import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js'; import { baseEmbed } from '../../ui/embeds.js';
/**
* Label shown for an action everywhere it is rendered (log channel, direct
* message, `/mod logs`, dashboard). Falls back to the raw action name, so a
* row written by another version still reads as something.
* @param {string} action
*/
export function moderationLabel(action) {
const meta = MODERATION_ACTIONS[action];
return meta ? `${meta.emoji} ${meta.label}` : action;
}
/** /**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08). * Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction * @param {import('discord.js').ChatInputCommandInteraction} interaction
@@ -81,7 +93,7 @@ export async function sendModerationLog(
const meta = MODERATION_ACTIONS[action]; const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color) const embed = baseEmbed(meta?.color)
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`) .setTitle(`🛡️ Modération — ${moderationLabel(action)}`)
.addFields( .addFields(
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true }, { name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Par', value: `<@${moderatorId}>`, inline: true }, { name: 'Par', value: `<@${moderatorId}>`, inline: true },
@@ -95,13 +107,28 @@ 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.
* @param guildId Server the sanction belongs to. A lifted ban targets someone
* who has left the server, so a plain `User` is accepted with an explicit id.
*/
export async function notifyTarget(member, payload, guildId = member.guild?.id) {
if (!readSetting('moderation.dmTarget', guildId)) 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];
const embed = baseEmbed(meta?.color) const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`) .setTitle(`Sanction sur ${guildName}`)
.setDescription( .setDescription(
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`, `Action : **${moderationLabel(action)}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
) )
.addFields({ name: 'Motif', value: reason || 'Non précisé' }); .addFields({ name: 'Motif', value: reason || 'Non précisé' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) }); if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
@@ -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). */
+133
View File
@@ -0,0 +1,133 @@
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { getRulesMessage, setRulesMessage } from '../../database/repositories/rules-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Rules of the server, written from the dashboard and kept in a single pinned
* message in `CHANNEL_RULES_ID` (M19).
*
* Saving edits the message already published, so the channel keeps one set of
* rules — same link, same position, and the pin survives. A new message is
* only sent when the bot has none yet, or when the previous one was deleted by
* hand.
*/
const log = createLogger('rules');
/** Discord refuses an embed description longer than that. */
export const RULES_MAX_LENGTH = 4000;
const TITLE = '📜 Règlement';
const rulesEmbed = (content) =>
baseEmbed(COLORS.primary)
.setTitle(TITLE)
.setDescription(content)
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
.setTimestamp(new Date());
/**
* Publishes the rules, editing the message already there when there is one.
* @param {import('discord.js').Client} client
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
*/
export async function publishRules(
client,
{ guildId, markdown, actorId = null, channelId = env.channels.rules },
) {
if (!channelId) {
throw new Error('Aucun salon des règles configuré : renseigne CHANNEL_RULES_ID dans le .env.');
}
const content = String(markdown ?? '').trim();
if (content === '') throw new Error('Le règlement est vide.');
if (content.length > RULES_MAX_LENGTH) {
throw new Error(`${RULES_MAX_LENGTH} caractères maximum pour un règlement.`);
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
}
const edited = await editPublishedRules(client, guildId, content);
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
// Only a brand new message has to be pinned: an edited one keeps its pin.
const pinned = edited
? true
: await message
.pin()
.then(() => true)
.catch((error) => {
// A bot without “Gérer les messages” still publishes the rules.
log.warn('Could not pin the rules message', error);
return false;
});
setRulesMessage({
guildId,
channelId,
messageId: message.id,
updatedBy: actorId,
});
logEvent({
guildId,
type: 'web.rules.published',
actorId,
payload: { channelId, messageId: message.id, pinned, edited: Boolean(edited) },
});
log.info('Rules saved from the dashboard', {
channelId,
messageId: message.id,
edited: Boolean(edited),
actor: actorId,
});
return {
messageId: message.id,
url: message.url ?? null,
channelId,
pinned,
edited: Boolean(edited),
};
}
/**
* Rewrites the message the bot published last time.
* @returns the edited message, or null when there is none to edit
*/
async function editPublishedRules(client, guildId, content) {
const stored = getRulesMessage(guildId);
if (!stored) return null;
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
if (!message?.editable) return null;
return message
.edit({ embeds: [rulesEmbed(content)] })
.then((edited) => edited ?? message)
.catch((error) => {
// A message deleted by hand, or one the bot may no longer edit, must not
// stop the publication: a fresh one takes its place.
log.warn('Could not edit the previous rules message', error);
return null;
});
}
/** What the dashboard needs to show the current state of the rules. */
export function rulesStatus(guildId, channelId = env.channels.rules) {
const stored = getRulesMessage(guildId);
return {
channelId: channelId || null,
configured: Boolean(channelId),
messageId: stored?.message_id ?? null,
publishedAt: stored?.updated_at ?? null,
publishedBy: stored?.updated_by ?? null,
};
}
+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 = [];
+80 -5
View File
@@ -1,6 +1,8 @@
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 } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { readSetting, writeSetting } from '../../config/guild-settings.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';
@@ -14,7 +16,8 @@ import {
removeNotificationChannel, removeNotificationChannel,
setNotificationChannel, setNotificationChannel,
} from '../../database/repositories/notification-repository.js'; } from '../../database/repositories/notification-repository.js';
import { sendModerationLog } from '../../services/moderation/moderation-service.js'; import { moderationLabel, sendModerationLog } from '../../services/moderation/moderation-service.js';
import { publishRules, rulesStatus } from '../../services/rules/rules-service.js';
import { badRequest, forbidden, notFound } from '../http.js'; import { badRequest, forbidden, notFound } from '../http.js';
/** Discord server management from the dashboard (M16-T05). */ /** Discord server management from the dashboard (M16-T05). */
@@ -200,7 +203,7 @@ export function registerDiscordRoutes(router) {
const reason = String(body.reason ?? '').trim() || 'Non précisé'; const reason = String(body.reason ?? '').trim() || 'Non précisé';
const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null; const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null;
if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) { if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) {
throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.'); throw badRequest('Une durée en millisecondes est requise pour une mise en sourdine.');
} }
const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`; const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`;
@@ -230,7 +233,7 @@ export function registerDiscordRoutes(router) {
durationMs, durationMs,
}); });
return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action }; return { ok: true, action, label: moderationLabel(action) };
}, },
{ access: ACCESS_LEVELS.STAFF }, { access: ACCESS_LEVELS.STAFF },
); );
@@ -291,6 +294,39 @@ export function registerDiscordRoutes(router) {
{ access: ACCESS_LEVELS.STAFF }, { access: ACCESS_LEVELS.STAFF },
); );
// --- Server rules ----------------------------------------------------------
router.get(
'/api/discord/rules',
() => ({ markdown: readSetting('rules.markdown', guildId()), ...rulesStatus(guildId()) }),
{ access: ACCESS_LEVELS.STAFF },
);
/** Publishes the rules, replacing the message the bot posted last time. */
router.post(
'/api/discord/rules',
async ({ context, body, actor }) => {
const markdown = writeSetting('rules.markdown', body.markdown, {
guildId: guildId(),
updatedBy: actor.userId,
});
try {
const published = await publishRules(context.client, {
guildId: guildId(),
markdown,
actorId: actor.userId,
});
return { ok: true, ...published, ...rulesStatus(guildId()) };
} catch (error) {
// The text is saved either way: a channel that is simply not configured
// yet must not throw away what was written.
throw badRequest(error.message);
}
},
{ access: ACCESS_LEVELS.DEV },
);
// --- Notification routing -------------------------------------------------- // --- Notification routing --------------------------------------------------
router.get( router.get(
'/api/discord/notifications', '/api/discord/notifications',
@@ -336,6 +372,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',
+13 -40
View File
@@ -1,9 +1,7 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { registerAuthRoutes } from '../auth/routes.js'; import { registerAuthRoutes } from '../auth/routes.js';
import { openEventStream } from '../events.js'; import { openEventStream } from '../events.js';
import { VERSION, buildAt } from '../services/build-info.js';
import { registerCommunityRoutes } from './community.js'; import { registerCommunityRoutes } from './community.js';
import { registerConfigurationRoutes } from './configuration.js'; import { registerConfigurationRoutes } from './configuration.js';
import { registerDeploymentRoutes } from './deployments.js'; import { registerDeploymentRoutes } from './deployments.js';
@@ -11,45 +9,13 @@ import { registerDiscordRoutes } from './discord.js';
import { registerLogRoutes } from './logs.js'; import { registerLogRoutes } from './logs.js';
import { registerOrganizationRoutes } from './organization.js'; import { registerOrganizationRoutes } from './organization.js';
import { registerOverviewRoutes } from './overview.js'; import { registerOverviewRoutes } from './overview.js';
import { registerProjectRoutes } from './projects.js';
import { registerReleaseRoutes } from './releases.js'; import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js'; import { registerRepositoryRoutes } from './repositories.js';
import { registerSearchRoutes } from './search.js';
import { registerSettingsRoutes } from './settings.js'; import { registerSettingsRoutes } from './settings.js';
import { registerStatusRoutes } from './status.js';
const here = path.dirname(fileURLToPath(import.meta.url)); import { registerWikiRoutes } from './wiki.js';
const VERSION = (() => {
try {
return JSON.parse(readFileSync(path.join(here, '../../../package.json'), 'utf8')).version;
} catch {
return 'inconnue';
}
})();
/**
* Newest file of the served interface.
*
* Deployments that ship an archive make it easy to look at a stale copy and
* wonder why a fix is missing; this gives the page something to state.
*/
const BUILD_AT = (() => {
const root = path.join(here, '../public');
let newest = 0;
const walk = (directory) => {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) walk(target);
else newest = Math.max(newest, statSync(target).mtimeMs);
}
};
try {
walk(root);
} catch {
return null;
}
return newest > 0 ? new Date(newest).toISOString() : null;
})();
/** /**
* Route registration order matters only for readability: the router matches on * Route registration order matters only for readability: the router matches on
@@ -65,13 +31,18 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
setupOnly: context.setupOnly, setupOnly: context.setupOnly,
uptimeMs: Date.now() - context.startedAt, uptimeMs: Date.now() - context.startedAt,
version: VERSION, version: VERSION,
buildAt: BUILD_AT, buildAt: buildAt(),
}), }),
{ public: true }, { public: true },
); );
registerAuthRoutes(router); registerAuthRoutes(router);
registerConfigurationRoutes(router); registerConfigurationRoutes(router);
// The public documentation stays reachable even while the bot is being set up.
registerWikiRoutes(router);
// So does the status page: a bot still being configured is exactly what an
// uptime monitor, or a visitor, would want to be told.
registerStatusRoutes(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(
@@ -88,11 +59,13 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
registerOverviewRoutes(router); registerOverviewRoutes(router);
registerOrganizationRoutes(router); registerOrganizationRoutes(router);
registerProjectRoutes(router);
registerRepositoryRoutes(router); registerRepositoryRoutes(router);
registerReleaseRoutes(router); registerReleaseRoutes(router);
registerDeploymentRoutes(router); registerDeploymentRoutes(router);
registerDiscordRoutes(router); registerDiscordRoutes(router);
registerCommunityRoutes(router); registerCommunityRoutes(router);
registerSearchRoutes(router);
registerSettingsRoutes(router); registerSettingsRoutes(router);
registerLogRoutes(router); registerLogRoutes(router);
return router; return router;
+527
View File
@@ -0,0 +1,527 @@
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
addCard,
addColumn,
countCardsInColumn,
countColumns,
createBoard,
getBoard,
getBoardByRepository,
getCard,
getColumn,
getOrgBoard,
listAssignees,
listBoards,
listCards,
listCardsForAssignee,
listColumns,
moveCard,
removeBoard,
removeCard,
removeColumn,
updateBoard,
updateCard,
updateColumn,
} from '../../database/repositories/project-repository.js';
import { repos, splitRepository } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { notify } from '../../services/notifications/notification-service.js';
import { badRequest, notFound } from '../http.js';
/**
* Kanban boards: one per repository, one for the organization (M18).
*
* Cards live here rather than in Gitea, whose project API is not stable across
* versions — a board that breaks whenever the forge hiccups is worse than none.
* A card may still point at an issue, and its real state is fetched when the
* forge answers.
*/
const log = createLogger('web:projects');
const guildId = () => env.discord.guildId;
/** `owner/repo#12`, the only shape a card may reference. */
const ISSUE_REF = /^[\w.-]+\/[\w.-]+#\d+$/;
const publicBoard = (board) => ({
id: board.id,
scope: board.scope,
repository: board.repository,
name: board.name,
description: board.description,
archived: board.archived,
createdAt: board.created_at,
updatedAt: board.updated_at,
});
const publicCard = (card) => ({
id: card.id,
columnId: card.column_id,
title: card.title,
body: card.body,
position: card.position,
assigneeId: card.assignee_id,
issueRef: card.issue_ref,
labels: card.labels,
dueAt: card.due_at,
createdBy: card.created_by,
updatedAt: card.updated_at,
});
const publicColumn = (column) => ({
id: column.id,
name: column.name,
position: column.position,
wipLimit: column.wip_limit,
isDone: column.is_done,
});
/** A card seen from outside its board: it has to say where it comes from (M19). */
const publicTask = (card) => ({
...publicCard(card),
boardId: card.board_id,
boardName: card.board_name,
boardScope: card.board_scope,
repository: card.repository,
columnName: card.column_name,
isDone: card.column_is_done,
doneColumnId: card.done_column_id ?? null,
});
function board(id) {
const found = getBoard(Number.parseInt(id, 10));
if (!found || found.guild_id !== guildId()) throw notFound('Tableau introuvable.');
return found;
}
const audit = (actor, type, payload) =>
logEvent({ guildId: guildId(), type, actorId: actor.userId, payload });
/**
* Resolves the referenced issues, one request per repository rather than per
* card. A forge that does not answer costs the cards their live state and
* nothing else.
*/
async function resolveIssues(cards) {
if (!isGiteaConfigured()) return {};
const byRepository = new Map();
for (const ref of new Set(cards.map((card) => card.issue_ref).filter(Boolean))) {
const [full, number] = ref.split('#');
if (!splitRepository(full)) continue;
if (!byRepository.has(full)) byRepository.set(full, new Set());
byRepository.get(full).add(number);
}
if (byRepository.size === 0) return {};
const resolved = {};
await Promise.all(
[...byRepository].map(async ([full, numbers]) => {
const { owner, repo } = splitRepository(full);
const issues = await repos.listIssues(owner, repo, { state: 'all', limit: 100 }).catch(() => []);
for (const issue of issues) {
if (!numbers.has(String(issue.number))) continue;
resolved[`${full}#${issue.number}`] = {
state: issue.state,
title: issue.title,
htmlUrl: issue.html_url,
};
}
}),
);
return resolved;
}
/** Announces a card movement in the community channel, when one is configured. */
async function announce(client, { board: owner, card, action, actor, column }) {
if (!client) return;
const titles = {
created: '🆕 Nouvelle carte',
moved: '➡️ Carte déplacée',
done: '✅ Carte terminée',
};
const embed = {
title: `${titles[action]} — ${owner.name}`,
description: card.title,
color: action === 'done' ? COLORS.success : COLORS.primary,
fields: [
{ name: 'Colonne', value: column?.name ?? '—', inline: true },
...(card.assignee_id ? [{ name: 'Assignée à', value: `<@${card.assignee_id}>`, inline: true }] : []),
...(card.issue_ref ? [{ name: 'Issue', value: card.issue_ref, inline: true }] : []),
],
footer: { text: `Par ${actor.displayName ?? actor.username ?? 'le tableau de bord'}` },
timestamp: new Date().toISOString(),
};
await notify(client, 'community', { embeds: [embed] }).catch((error) =>
log.debug('Could not announce the card movement', error),
);
}
export function registerProjectRoutes(router) {
// --- My tasks --------------------------------------------------------------
/**
* What one member carries, across every board (M19).
*
* The boards answer « where does the work stand ». This answers « what am I
* on », which is the question someone actually opens a dashboard with, and no
* board alone can answer it once the work is spread over several.
*/
router.get(
'/api/me/tasks',
async ({ query, actor }) => {
const assigneeId = String(query.get('assignee') ?? '').trim() || actor.userId;
if (!assigneeId) throw badRequest('Aucun membre à qui rattacher des cartes.');
const cards = listCardsForAssignee(guildId(), assigneeId);
const today = new Date().toISOString().slice(0, 10);
const open = cards.filter((entry) => !entry.column_is_done);
const dated = (entry, test) => entry.due_at && test(String(entry.due_at).slice(0, 10));
return {
assigneeId,
self: assigneeId === actor.userId,
assignees: listAssignees(guildId()),
counts: {
total: cards.length,
open: open.length,
done: cards.length - open.length,
overdue: open.filter((entry) => dated(entry, (due) => due < today)).length,
dueToday: open.filter((entry) => dated(entry, (due) => due === today)).length,
},
cards: cards.map(publicTask),
// Resolving costs a round trip to the forge, which the sidebar counter
// has no use for — it asks for the numbers and skips it.
issues: query.get('issues') === '0' ? {} : await resolveIssues(cards),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Boards ----------------------------------------------------------------
router.get(
'/api/projects',
() => ({
boards: listBoards(guildId()).map((entry) => ({
...publicBoard(entry),
columns: countColumns(entry.id),
cards: listCards(entry.id).length,
})),
orgBoard: getOrgBoard(guildId()) ? publicBoard(getOrgBoard(guildId())) : null,
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/projects',
({ body, actor }) => {
const scope = body.scope === 'org' ? 'org' : 'repo';
const repository = scope === 'repo' ? String(body.repository ?? '').trim() : null;
if (scope === 'repo' && !splitRepository(repository)) {
throw badRequest('Dépôt attendu au format `organisation/depot`.');
}
if (scope === 'org' && getOrgBoard(guildId())) {
throw badRequest('L’organisation a déjà son tableau.');
}
if (repository && getBoardByRepository(guildId(), repository)) {
throw badRequest(`Le dépôt ${repository} a déjà son tableau.`);
}
const name = String(body.name ?? '').trim() || (repository ?? 'Organisation');
const created = createBoard({
guildId: guildId(),
scope,
repository,
name,
description: body.description ? String(body.description) : null,
createdBy: actor.userId,
});
audit(actor, 'web.project.create', { board: created.id, scope, repository });
return publicBoard(created);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/projects/:id',
async ({ params }) => {
const found = board(params.id);
const cards = listCards(found.id);
return {
...publicBoard(found),
columns: listColumns(found.id).map((column) => ({
...publicColumn(column),
cards: cards.filter((card) => card.column_id === column.id).map(publicCard),
})),
issues: await resolveIssues(cards),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id',
({ params, body, actor }) => {
const found = board(params.id);
const updated = updateBoard(found.id, {
name: body.name === undefined ? undefined : String(body.name).trim(),
description: body.description === undefined ? undefined : String(body.description),
archived: body.archived,
});
audit(actor, 'web.project.update', { board: found.id });
return publicBoard(updated);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id',
({ params, body, actor }) => {
const found = board(params.id);
if (body.confirm !== found.name) {
throw badRequest(`Pour confirmer, renvoie exactement « ${found.name} ».`);
}
removeBoard(found.id);
audit(actor, 'web.project.delete', { board: found.id, name: found.name });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
// --- Columns ---------------------------------------------------------------
router.post(
'/api/projects/:id/columns',
({ params, body, actor }) => {
const found = board(params.id);
const name = String(body.name ?? '').trim();
if (name === '') throw badRequest('Nom de colonne manquant.');
const column = addColumn({
boardId: found.id,
name,
wipLimit: Number.parseInt(body.wipLimit ?? 0, 10) || 0,
isDone: Boolean(body.isDone),
});
audit(actor, 'web.project.column.create', { board: found.id, column: column.id });
return publicColumn(column);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id/columns/:columnId',
({ params, body }) => {
board(params.id);
const column = getColumn(Number.parseInt(params.columnId, 10));
if (!column) throw notFound('Colonne introuvable.');
return publicColumn(
updateColumn(column.id, {
name: body.name === undefined ? undefined : String(body.name).trim(),
wipLimit: body.wipLimit,
isDone: body.isDone,
position: body.position,
}),
);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id/columns/:columnId',
({ params, actor }) => {
const found = board(params.id);
if (countColumns(found.id) <= 1) throw badRequest('Un tableau garde au moins une colonne.');
removeColumn(Number.parseInt(params.columnId, 10));
audit(actor, 'web.project.column.delete', { board: found.id, column: params.columnId });
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
// --- Cards -----------------------------------------------------------------
router.post(
'/api/projects/:id/cards',
async ({ params, body, actor, context }) => {
const found = board(params.id);
const title = String(body.title ?? '').trim();
if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.');
const columnId = Number.parseInt(body.columnId ?? 0, 10);
const column = getColumn(columnId);
if (!column || column.board_id !== found.id) throw badRequest('Colonne inconnue sur ce tableau.');
const issueRef = String(body.issueRef ?? '').trim();
if (issueRef && !ISSUE_REF.test(issueRef)) {
throw badRequest('Référence attendue au format `organisation/depot#12`.');
}
const card = addCard({
boardId: found.id,
columnId,
title,
body: body.body ? String(body.body) : null,
assigneeId: body.assigneeId ? String(body.assigneeId) : null,
issueRef: issueRef || null,
labels: Array.isArray(body.labels) ? body.labels.map(String) : [],
dueAt: body.dueAt ? String(body.dueAt) : null,
createdBy: actor.userId,
});
audit(actor, 'web.project.card.create', { board: found.id, card: card.id });
await announce(context.client, { board: found, card, action: 'created', actor, column });
return publicCard(card);
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/projects/:id/cards/:cardId',
({ params, body, actor }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
if (body.issueRef !== undefined && body.issueRef && !ISSUE_REF.test(String(body.issueRef))) {
throw badRequest('Référence attendue au format `organisation/depot#12`.');
}
const updated = updateCard(card.id, {
title: body.title === undefined ? undefined : String(body.title).trim(),
body: body.body === undefined ? undefined : String(body.body),
assigneeId: body.assigneeId,
issueRef: body.issueRef,
labels: body.labels === undefined ? undefined : body.labels.map(String),
dueAt: body.dueAt,
});
audit(actor, 'web.project.card.update', { board: found.id, card: card.id });
return publicCard(updated);
},
{ access: ACCESS_LEVELS.STAFF },
);
/** Drag and drop: the card lands in a column, at a rank. */
router.post(
'/api/projects/:id/cards/:cardId/move',
async ({ params, body, actor, context }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
const columnId = Number.parseInt(body.columnId ?? 0, 10);
const column = getColumn(columnId);
if (!column || column.board_id !== found.id) throw badRequest('Colonne inconnue sur ce tableau.');
// The limit is a warning, not a wall: it says the column is overloaded
// without stopping someone mid-gesture.
const overloaded =
column.wip_limit > 0 &&
card.column_id !== columnId &&
countCardsInColumn(columnId) >= column.wip_limit;
const moved = moveCard(card.id, { columnId, position: Number.parseInt(body.position ?? 0, 10) });
audit(actor, 'web.project.card.move', { board: found.id, card: card.id, column: columnId });
if (card.column_id !== columnId) {
await announce(context.client, {
board: found,
card: moved,
action: column.is_done ? 'done' : 'moved',
actor,
column,
});
}
return { card: publicCard(moved), overloaded };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.delete(
'/api/projects/:id/cards/:cardId',
({ params, actor }) => {
const found = board(params.id);
const card = getCard(Number.parseInt(params.cardId, 10));
if (!card || card.board_id !== found.id) throw notFound('Carte introuvable.');
removeCard(card.id);
audit(actor, 'web.project.card.delete', { board: found.id, card: card.id });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
/**
* Pulls issues from Gitea onto the board.
*
* An issue already on the board is skipped rather than duplicated, so the
* button can be pressed again after a sprint without cleaning up after it.
*/
router.post(
'/api/projects/:id/import',
async ({ params, body, actor }) => {
const found = board(params.id);
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré.');
const repository = String(body.repository ?? found.repository ?? '').trim();
const parts = splitRepository(repository);
if (!parts) throw badRequest('Dépôt attendu au format `organisation/depot`.');
const state = body.state === 'all' ? 'all' : 'open';
const columns = listColumns(found.id);
if (columns.length === 0) throw badRequest('Ce tableau n’a aucune colonne.');
// Falls back to the first column that is not the finished one: importing
// straight into « Terminé » is never what anyone means.
const requested = body.columnId ? getColumn(Number.parseInt(body.columnId, 10)) : null;
const target =
requested && requested.board_id === found.id
? requested
: (columns.find((column) => !column.is_done) ?? columns[0]);
const existing = new Set(
listCards(found.id)
.map((card) => card.issue_ref)
.filter(Boolean),
);
const issues = await repos.listIssues(parts.owner, parts.repo, { state, limit: 100 });
let imported = 0;
for (const issue of issues) {
const ref = `${repository}#${issue.number}`;
if (existing.has(ref)) continue;
addCard({
boardId: found.id,
columnId: target.id,
title: issue.title,
body: issue.body ? String(issue.body).slice(0, 2000) : null,
issueRef: ref,
labels: (issue.labels ?? []).map((label) => label.name),
dueAt: issue.due_date ? String(issue.due_date).slice(0, 10) : null,
createdBy: actor.userId,
});
imported += 1;
}
audit(actor, 'web.project.import', { board: found.id, repository, state, imported });
return {
imported,
skipped: issues.length - imported,
found: issues.length,
column: target.name,
repository,
};
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+159
View File
@@ -0,0 +1,159 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { searchCards } from '../../database/repositories/project-repository.js';
import { searchPublished } from '../../database/repositories/wiki-repository.js';
import { org } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { pagePath } from '../services/wiki-seed.js';
/**
* One search across everything the dashboard knows (M19).
*
* Until now, finding something meant knowing which tab it lived in — which is
* fine once you have learned the panel and hopeless before. Each source is
* asked independently and a source that fails is simply left out: a forge that
* is down must not take the wiki and the boards with it.
*/
const log = createLogger('web:search');
const guildId = () => env.discord.guildId;
/** Below this a search matches half the organization, which helps nobody. */
const MIN_TERM = 2;
const PER_GROUP = 6;
/**
* Repository lists change by the hour and are asked for on every keystroke, so
* they are kept briefly. The stamp only moves on success, which turns a forge
* outage into slightly old results rather than none.
*/
const REPO_TTL_MS = 60_000;
let repoCache = { at: 0, repositories: [] };
async function repositories() {
if (!isGiteaConfigured()) return [];
if (Date.now() - repoCache.at < REPO_TTL_MS) return repoCache.repositories;
const list = await org.listRepos({ limit: 50 }).catch((error) => {
log.debug('Falling back to the cached repository list', error);
return null;
});
if (list) repoCache = { at: Date.now(), repositories: list };
return repoCache.repositories;
}
const contains = (haystack, needle) =>
String(haystack ?? '')
.toLowerCase()
.includes(needle);
async function searchRepositories(needle) {
const list = await repositories();
return list
.filter(
(repository) => contains(repository.full_name, needle) || contains(repository.description, needle),
)
.slice(0, PER_GROUP)
.map((repository) => ({
kind: 'repository',
title: repository.full_name,
subtitle: repository.description || 'Dépôt de l’organisation',
href: `#/repos/${repository.full_name}`,
badge: repository.private ? 'Privé' : null,
}));
}
async function searchIssues(needle) {
if (!isGiteaConfigured()) return [];
// `all` rather than `open`: someone searching for an issue by name usually
// wants the one they remember, closed or not.
const issues = await org.searchIssues({ q: needle, state: 'all', limit: PER_GROUP }).catch((error) => {
log.debug('The forge did not answer the issue search', error);
return [];
});
return issues.slice(0, PER_GROUP).map((issue) => ({
kind: issue.pull_request ? 'pull' : 'issue',
title: issue.title,
subtitle: `${issue.repository?.full_name ?? 'Gitea'}#${issue.number}`,
href: issue.html_url,
external: true,
badge: issue.state === 'closed' ? 'Fermée' : 'Ouverte',
}));
}
function searchBoardCards(needle) {
return searchCards(guildId(), needle, PER_GROUP).map((card) => ({
kind: 'card',
title: card.title,
subtitle: `${card.board_name} · ${card.column_name}`,
href: `#/projects/${card.board_id}`,
badge: card.column_is_done ? 'Terminée' : (card.issue_ref ?? null),
}));
}
function searchWiki(needle) {
return searchPublished(needle)
.slice(0, PER_GROUP)
.map((page) => ({
kind: 'wiki',
title: page.title,
subtitle: page.summary || page.category,
href: pagePath(page.slug),
external: true,
badge: page.category,
}));
}
/**
* Members come from the cache rather than a fetch: pulling the roster from
* Discord on every keystroke would be slow and rate-limited, and whoever is
* being looked for is almost always already cached.
*/
function searchMembers(client, needle) {
const guild = client?.guilds?.cache?.get(guildId());
if (!guild) return [];
return [...guild.members.cache.values()]
.filter(
(member) =>
contains(member.user.username, needle) ||
contains(member.displayName, needle) ||
member.id === needle,
)
.slice(0, PER_GROUP)
.map((member) => ({
kind: 'member',
title: member.displayName,
subtitle: `@${member.user.username}`,
href: `#/discord?member=${encodeURIComponent(member.user.username)}`,
badge: member.user.bot ? 'Bot' : null,
}));
}
export function registerSearchRoutes(router) {
router.get(
'/api/search',
async ({ query, context }) => {
const term = String(query.get('q') ?? '').trim();
if (term.length < MIN_TERM) return { term, results: [], truncated: false };
const needle = term.toLowerCase();
const [repos, issues] = await Promise.all([searchRepositories(needle), searchIssues(term)]);
// Local sources first: they are exact, instant, and what the panel owns.
const results = [
...searchBoardCards(term),
...repos,
...issues,
...searchWiki(term),
...searchMembers(context.client, needle),
];
return { term, results, truncated: results.length >= PER_GROUP * 5 };
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+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 },
); );
+21
View File
@@ -0,0 +1,21 @@
import { env } from '../../config/env.js';
import { notFound } from '../http.js';
import { statusSnapshot } from '../services/status-service.js';
/**
* Machine-readable twin of the public status page (M19).
*
* `/api/health` says whether the process is alive, which is what a load
* balancer asks. This says what state the service is in, which is what a person
* — or an uptime monitor with a dashboard — asks.
*/
export function registerStatusRoutes(router) {
router.get(
'/api/status',
async ({ context }) => {
if (!env.web.publicStatus) throw notFound('La page de statut est désactivée.');
return statusSnapshot(context);
},
{ public: true },
);
}
+211
View File
@@ -0,0 +1,211 @@
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';
import { pagePath } from '../services/wiki-seed.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,
path: pagePath(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 },
);
}
+2
View File
@@ -122,6 +122,8 @@ export function topicForPath(pathname) {
case 'repositories': case 'repositories':
case 'organization': case 'organization':
return 'gitea'; return 'gitea';
case 'projects':
return 'projects';
case 'discord': case 'discord':
return 'discord'; return 'discord';
case 'community': case 'community':
+39 -3
View File
@@ -59,6 +59,24 @@ export function sendJson(response, status, payload) {
response.end(body); response.end(body);
} }
/**
* Sends a finished HTML document. Public pages carry a relaxed policy: they
* embed no script of their own, and must stay readable to whoever fetches them.
*/
export function sendHtml(response, status, html) {
const body = Buffer.from(html, 'utf8');
response.writeHead(status, {
...SECURITY_HEADERS,
'Content-Security-Policy':
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'none'; " +
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': body.length,
'Cache-Control': 'no-cache',
});
response.end(body);
}
export function sendEmpty(response, status, headers = {}) { export function sendEmpty(response, status, headers = {}) {
response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end(); response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end();
} }
@@ -132,7 +150,7 @@ export function clientIp(request) {
* Serves a file from `root`, refusing anything that escapes it. * Serves a file from `root`, refusing anything that escapes it.
* Returns false when the file does not exist, so the caller can fall back. * Returns false when the file does not exist, so the caller can fall back.
*/ */
export async function sendStatic(response, root, requestPath, { fallback = null } = {}) { export async function sendStatic(response, root, requestPath, { fallback = null, request = null } = {}) {
const relative = decodeURIComponent(requestPath).replace(/^\/+/, ''); const relative = decodeURIComponent(requestPath).replace(/^\/+/, '');
const resolved = path.resolve(root, relative || 'index.html'); const resolved = path.resolve(root, relative || 'index.html');
const target = resolved.startsWith(path.resolve(root)) ? resolved : null; const target = resolved.startsWith(path.resolve(root)) ? resolved : null;
@@ -150,12 +168,30 @@ export async function sendStatic(response, root, requestPath, { fallback = null
if (!info?.isFile()) return false; if (!info?.isFile()) return false;
const extension = path.extname(file).toLowerCase(); const extension = path.extname(file).toLowerCase();
// `no-cache` alone tells a cache to revalidate, but without a validator it has
// nothing to revalidate against — which is how a browser or a CDN ends up
// serving a front-end older than the API it talks to.
const etag = `"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`;
if (request?.headers?.['if-none-match'] === etag) {
response.writeHead(304, { ...SECURITY_HEADERS, ETag: etag }).end();
return true;
}
response.writeHead(200, { response.writeHead(200, {
...SECURITY_HEADERS, ...SECURITY_HEADERS,
'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream', 'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream',
'Content-Length': info.size, 'Content-Length': info.size,
// The SPA shell must never be cached, its modules are revalidated on each load. // Every module is fetched fresh rather than revalidated.
'Cache-Control': extension === '.html' ? 'no-store' : 'no-cache', //
// A dashboard is a handful of small files loaded by one person at a time,
// so the bandwidth saved by caching is worth less than the failure it
// causes: modules cache independently, so a partial revalidation leaves a
// page running one version of itself and another of its helpers, which
// surfaces as an error inside a feature rather than as a stale cache.
'Cache-Control': 'no-store',
ETag: etag,
'Last-Modified': new Date(info.mtimeMs).toUTCString(),
}); });
createReadStream(file).pipe(response); createReadStream(file).pipe(response);
return true; return true;
+91 -16
View File
@@ -1,6 +1,8 @@
import { api } from './core/api.js'; import { api } from './core/api.js';
import { h, mount, qs } from './core/dom.js'; import { h, mount, qs } from './core/dom.js';
import { onStatus, resetSubscriptions, startLive } from './core/live.js'; import { onStatus, resetSubscriptions, startLive } from './core/live.js';
import { activePath, highlight } from './core/nav.js';
import { bindPalette, openPalette } from './core/palette.js';
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js'; import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
/** Shell, navigation and hash routing of the dashboard (M16-T11). */ /** Shell, navigation and hash routing of the dashboard (M16-T11). */
@@ -20,6 +22,14 @@ const ROUTES = [
module: './views/overview.js', module: './views/overview.js',
level: LEVELS.STAFF, level: LEVELS.STAFF,
}, },
{
path: 'tasks',
icon: '✓',
label: 'Mes tâches',
group: 'Pilotage',
module: './views/tasks.js',
level: LEVELS.STAFF,
},
{ {
path: 'org', path: 'org',
icon: '⬡', icon: '⬡',
@@ -28,6 +38,14 @@ const ROUTES = [
module: './views/organization.js', module: './views/organization.js',
level: LEVELS.STAFF, level: LEVELS.STAFF,
}, },
{
path: 'projects',
icon: '▦',
label: 'Projets',
group: 'Pilotage',
module: './views/projects.js',
level: LEVELS.STAFF,
},
{ {
path: 'repos', path: 'repos',
icon: '◫', icon: '◫',
@@ -68,6 +86,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: '≡',
@@ -130,7 +156,7 @@ const currentRoute = () => {
const raw = window.location.hash.replace(/^#\/?/, ''); const raw = window.location.hash.replace(/^#\/?/, '');
const [path] = raw.split('?'); const [path] = raw.split('?');
const segments = path.split('/').filter(Boolean); const segments = path.split('/').filter(Boolean);
return { segments, path }; return { segments, path, active: activePath(window.location.hash) };
}; };
/** /**
@@ -140,18 +166,8 @@ const currentRoute = () => {
* its own — otherwise it keeps pointing at the page you arrived on. * its own — otherwise it keeps pointing at the page you arrived on.
*/ */
function highlightNav(scope = document) { function highlightNav(scope = document) {
const { segments } = currentRoute(); const active = highlight(scope, window.location.hash);
const active = segments[0] ?? '';
const route = ROUTES.find((entry) => entry.path === active); const route = ROUTES.find((entry) => entry.path === active);
for (const link of scope.querySelectorAll('.nav a')) {
// Compare the route the link carries, not its href: a trailing slash or a
// query string in the hash must not make an entry look inactive.
const current = link.dataset.route === active;
link.classList.toggle('active', current);
if (current) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot';
} }
@@ -183,10 +199,20 @@ function liveIndicator() {
return node; return node;
} }
function sidebar() { /**
const visible = ROUTES.filter( * Pages the visitor can actually reach. Shared with the palette so a search
(route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'), * never offers a page that would answer with « niveau d’accès supérieur ».
*/
function visibleRoutes() {
return ROUTES.filter(
(route) => (state.me?.accessLevel ?? 0) >= route.level && (!route.advanced || state.mode === 'advanced'),
); );
}
const SHORTCUT = navigator.userAgent.includes('Mac') ? '⌘K' : 'Ctrl+K';
function sidebar() {
const visible = visibleRoutes();
const groups = []; const groups = [];
for (const route of visible) { for (const route of visible) {
@@ -204,6 +230,18 @@ function sidebar() {
h('img', { src: 'favicon.svg', alt: '' }), h('img', { src: 'favicon.svg', alt: '' }),
h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })), h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })),
), ),
h(
'button',
{
class: 'nav-search',
type: 'button',
onClick: () => openPalette(visibleRoutes()),
title: `Recherche globale (${SHORTCUT})`,
},
h('span', { class: 'nav-icon', text: '⌕' }),
h('span', { text: 'Rechercher' }),
h('kbd', { text: SHORTCUT }),
),
h( h(
'nav', 'nav',
{ class: 'nav' }, { class: 'nav' },
@@ -215,6 +253,9 @@ function sidebar() {
{ href: `#/${route.path}`, dataset: { route: route.path } }, { href: `#/${route.path}`, dataset: { route: route.path } },
h('span', { class: 'nav-icon', text: route.icon }), h('span', { class: 'nav-icon', text: route.icon }),
h('span', { text: route.label }), h('span', { text: route.label }),
// A page you have to open to know whether it needs you is a page
// you stop opening; the count is what makes it a morning habit.
route.path === 'tasks' && h('span', { class: 'nav-count', hidden: true }),
), ),
), ),
]), ]),
@@ -279,6 +320,7 @@ async function renderView(host) {
const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); const route = ROUTES.find((entry) => entry.path === (segments[0] ?? ''));
resetSubscriptions(); resetSubscriptions();
highlightNav(); highlightNav();
refreshTaskCount();
host.scrollIntoView?.({ block: 'start' }); host.scrollIntoView?.({ block: 'start' });
if (!route) { if (!route) {
@@ -302,7 +344,9 @@ async function renderView(host) {
const module = await import(route.module); const module = await import(route.module);
await module.render(host, { params: segments.slice(1), state }); await module.render(host, { params: segments.slice(1), state });
} catch (error) { } catch (error) {
mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message }))); console.error('[fws] échec de la vue', error);
const { errorBox } = await import('./core/ui.js');
mount(host, errorBox(error.message, { retry: () => renderView(host), error }));
} }
} }
@@ -325,9 +369,39 @@ export function render() {
mount(app, shell); mount(app, shell);
applyModeButtons(shell); applyModeButtons(shell);
highlightNav(shell); highlightNav(shell);
refreshTaskCount();
renderView(main); renderView(main);
} }
/**
* Open cards assigned to the viewer, shown on the sidebar entry.
*
* Asked for with `issues=0`: the counter needs a number, not a round trip to
* the forge to resolve every linked issue. Throttled, because navigating is not
* a reason to ask again.
*/
const TASK_COUNT_TTL_MS = 60_000;
let taskCountAt = 0;
async function refreshTaskCount(force = false) {
if (!qs('.nav-count')) return;
if (!force && Date.now() - taskCountAt < TASK_COUNT_TTL_MS) return;
taskCountAt = Date.now();
const data = await api.get('/api/me/tasks', { issues: '0' }).catch(() => null);
// The shell may have been rebuilt while the request was in flight.
const node = qs('.nav-count');
if (!node || !data) return;
const { open, overdue } = data.counts;
node.textContent = open > 99 ? '99+' : String(open);
node.hidden = open === 0;
node.dataset.tone = overdue > 0 ? 'late' : 'normal';
node.title = overdue > 0 ? `${overdue} carte(s) en retard` : `${open} carte(s) à faire`;
}
document.addEventListener('fws:tasks-changed', () => refreshTaskCount(true));
/** Names the interface actually being served, archive deployments being easy to get wrong. */ /** Names the interface actually being served, archive deployments being easy to get wrong. */
async function showBuild() { async function showBuild() {
const health = await api.get('/api/health').catch(() => null); const health = await api.get('/api/health').catch(() => null);
@@ -354,6 +428,7 @@ async function boot() {
startLive(); startLive();
showBuild(); showBuild();
bindPalette(visibleRoutes);
window.addEventListener('hashchange', () => { window.addEventListener('hashchange', () => {
const main = qs('.main'); const main = qs('.main');
+1
View File
@@ -71,6 +71,7 @@ function connect() {
'gitea', 'gitea',
'discord', 'discord',
'community', 'community',
'projects',
'settings', 'settings',
]) { ]) {
source.addEventListener(topic, (event) => { source.addEventListener(topic, (event) => {
+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 };
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Which navigation entry is the current one (M16-T11).
*
* Kept apart from the shell so it can be tested: getting this wrong leaves the
* sidebar pointing at a page you are not on, which is the kind of bug that
* looks like nothing and gets reported three times.
*/
/**
* First segment of a hash route, which is what a sidebar entry stands for.
* `#/repos/FWS/Arch` and `#/repos` are the same entry; `#/releases?repo=x` too.
*/
export function activePath(hash = '') {
const raw = String(hash).replace(/^#\/?/, '');
const [path] = raw.split('?');
const [first = ''] = path.split('/').filter(Boolean);
return first;
}
/**
* Marks the matching link inside `scope` and clears the others.
* Returns the active path, so a caller can retitle the page from it.
*/
export function highlight(scope, hash = '') {
const active = activePath(hash);
for (const link of scope.querySelectorAll('.nav a')) {
// Compare the route a link carries, not its href: a trailing slash or a
// query string must not make an entry look inactive.
const current = (link.dataset.route ?? '') === active;
link.classList.toggle('active', current);
if (current) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
return active;
}
+251
View File
@@ -0,0 +1,251 @@
import { api } from './api.js';
import { h, mount } from './dom.js';
/**
* Command palette: one search across everything (M19).
*
* Before this, finding something meant knowing which tab it lived in. Pages are
* matched in the browser so the palette is useful the instant it opens, even
* with the forge down; everything else comes from `/api/search`.
*/
const DEBOUNCE_MS = 180;
const MIN_REMOTE = 2;
const GROUPS = [
{ kind: 'page', label: 'Pages', icon: '◈' },
{ kind: 'card', label: 'Cartes', icon: '▦' },
{ kind: 'repository', label: 'Dépôts', icon: '◫' },
{ kind: 'issue', label: 'Issues', icon: '◇' },
{ kind: 'pull', label: 'Pull requests', icon: '⑂' },
{ kind: 'wiki', label: 'Wiki', icon: '📖' },
{ kind: 'member', label: 'Membres', icon: '☺' },
];
const ICONS = Object.fromEntries(GROUPS.map((group) => [group.kind, group.icon]));
const RANK = Object.fromEntries(GROUPS.map((group, index) => [group.kind, index]));
/**
* Sorts the results into their groups, keeping the order inside each one.
*
* The forge returns issues and pull requests interleaved, which would print a
* heading above almost every line.
*/
export const grouped = (results) =>
results
.map((result, index) => ({ result, index }))
.sort((a, b) => (RANK[a.result.kind] ?? 99) - (RANK[b.result.kind] ?? 99) || a.index - b.index)
.map((entry) => entry.result);
let open = false;
const matches = (text, needle) =>
String(text ?? '')
.toLowerCase()
.includes(needle);
/** Pages the visitor may actually reach, matched locally on label and group. */
export function localPages(pages, needle) {
return pages
.filter((page) => needle === '' || matches(page.label, needle) || matches(page.group, needle))
.slice(0, 8)
.map((page) => ({
kind: 'page',
title: page.label,
subtitle: page.group,
href: `#/${page.path}`,
}));
}
function go(result) {
if (result.external) window.open(result.href, '_blank', 'noreferrer');
else window.location.hash = result.href.replace(/^#/, '');
}
/**
* Opens the palette. `pages` is the navigation the visitor can see, so a page
* they have no access to never shows up as a result.
*/
export function openPalette(pages = []) {
if (open) return;
open = true;
const restoreFocus = document.activeElement;
const overlay = h('div', { class: 'overlay palette-overlay' });
const list = h('div', { class: 'palette-list', role: 'listbox', id: 'palette-results' });
const hint = h('div', { class: 'palette-hint' });
const field = h('input', {
class: 'palette-input',
type: 'search',
placeholder: 'Rechercher une page, un dépôt, une carte, une issue…',
'aria-label': 'Recherche globale',
'aria-controls': 'palette-results',
autocomplete: 'off',
spellcheck: 'false',
});
let results = [];
let cursor = 0;
let timer = null;
/** Answers can arrive out of order; only the latest query may draw. */
let sequence = 0;
const close = () => {
open = false;
clearTimeout(timer);
document.removeEventListener('keydown', onKey, true);
overlay.remove();
restoreFocus?.focus?.();
};
const draw = () => {
if (results.length === 0) {
mount(list, h('p', { class: 'palette-empty', text: 'Aucun résultat.' }));
return;
}
cursor = Math.max(0, Math.min(cursor, results.length - 1));
const nodes = [];
let group = null;
for (const [index, result] of results.entries()) {
if (result.kind !== group) {
group = result.kind;
const label = GROUPS.find((entry) => entry.kind === group)?.label ?? group;
nodes.push(h('div', { class: 'palette-group', text: label }));
}
nodes.push(
h(
'button',
{
class: index === cursor ? 'palette-item active' : 'palette-item',
type: 'button',
role: 'option',
'aria-selected': index === cursor ? 'true' : 'false',
// `mousedown` rather than `click`: the input keeps focus, so the
// palette does not close under the pointer before the choice lands.
onMousedown: (event) => {
event.preventDefault();
close();
go(result);
},
// Guarded: a redraw replaces the node under the pointer, which
// fires `mouseenter` again — without this the two loop forever.
onMouseenter: () => {
if (cursor === index) return;
cursor = index;
draw();
},
},
h('span', { class: 'palette-icon', text: ICONS[result.kind] ?? '·' }),
h(
'span',
{ class: 'palette-text' },
h('strong', { text: result.title }),
result.subtitle && h('span', { class: 'muted', text: result.subtitle }),
),
result.badge && h('span', { class: 'palette-badge', text: result.badge }),
result.external && h('span', { class: 'palette-external', text: '↗', title: 'Ouvre un onglet' }),
),
);
}
mount(list, nodes);
list.querySelector('.palette-item.active')?.scrollIntoView({ block: 'nearest' });
};
const search = async (term) => {
const needle = term.trim().toLowerCase();
const local = localPages(pages, needle);
results = grouped(local);
cursor = 0;
hint.textContent = needle.length < MIN_REMOTE ? 'Tape au moins 2 caractères pour chercher partout.' : '';
draw();
if (needle.length < MIN_REMOTE) return;
const mine = ++sequence;
const remote = await api.get('/api/search', { q: term.trim() }).catch(() => null);
if (mine !== sequence || !open) return;
if (!remote) {
hint.textContent = 'La recherche étendue n’a pas répondu ; seules les pages sont listées.';
return;
}
hint.textContent = '';
// Pages stay first: they are the fastest thing the palette can do.
results = grouped([...local, ...remote.results]);
draw();
};
const onKey = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
close();
} else if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) {
event.preventDefault();
cursor = results.length === 0 ? 0 : (cursor + 1) % results.length;
draw();
} else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) {
event.preventDefault();
cursor = results.length === 0 ? 0 : (cursor - 1 + results.length) % results.length;
draw();
} else if (event.key === 'Enter' && results[cursor]) {
event.preventDefault();
const chosen = results[cursor];
close();
go(chosen);
}
};
field.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(() => search(field.value), DEBOUNCE_MS);
});
overlay.addEventListener('click', (event) => {
if (event.target === overlay) close();
});
document.addEventListener('keydown', onKey, true);
overlay.append(
h(
'div',
{ class: 'palette', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Recherche globale' },
h('div', { class: 'palette-head' }, h('span', { class: 'palette-prompt', text: '⌕' }), field),
list,
h(
'footer',
{ class: 'palette-foot' },
hint,
h('span', { class: 'muted', text: '↑ ↓ pour naviguer · ↵ pour ouvrir · Échap pour fermer' }),
),
),
);
document.body.append(overlay);
field.focus();
search('');
}
/**
* Binds ⌘K / Ctrl+K globally.
*
* `/` opens it too, but only when nothing is being typed into: stealing a
* slash from someone writing a release note would be unforgivable.
*/
export function bindPalette(pages) {
const typing = () =>
['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName) ||
document.activeElement?.isContentEditable;
document.addEventListener('keydown', (event) => {
const combo = (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k';
if (!combo && !(event.key === '/' && !typing())) return;
event.preventDefault();
openPalette(pages());
});
}
+58 -9
View File
@@ -80,7 +80,7 @@ export function toggle(checked, onChange, label) {
* Renders a table. Each column is `{ key, label, render?, className? }`; * Renders a table. Each column is `{ key, label, render?, className? }`;
* `render` returns a Node or a string. * `render` returns a Node or a string.
*/ */
export function table(columns, rows, { empty = 'Rien à afficher pour le moment.' } = {}) { export function table(columns, rows, { empty = 'Rien à afficher pour le moment.', rowHref = null } = {}) {
if (!rows || rows.length === 0) { if (!rows || rows.length === 0) {
// An empty state is where people look for the action that fills it, so it // An empty state is where people look for the action that fills it, so it
// accepts a node and not only a sentence. // accepts a node and not only a sentence.
@@ -107,10 +107,11 @@ export function table(columns, rows, { empty = 'Rien à afficher pour le moment.
h( h(
'tbody', 'tbody',
{}, {},
rows.map((row) => rows.map((row) => {
h( const target = rowHref?.(row) ?? null;
const line = h(
'tr', 'tr',
{}, target ? { class: 'row-link', tabindex: '0', role: 'link' } : {},
columns.map((column) => { columns.map((column) => {
const cell = h('td', { class: column.className ?? '' }); const cell = h('td', { class: column.className ?? '' });
const value = column.render ? column.render(row) : row[column.key]; const value = column.render ? column.render(row) : row[column.key];
@@ -118,8 +119,25 @@ export function table(columns, rows, { empty = 'Rien à afficher pour le moment.
else cell.textContent = value === null || value === undefined ? '—' : String(value); else cell.textContent = value === null || value === undefined ? '—' : String(value);
return cell; return cell;
}), }),
), );
),
if (target) {
// A control inside the row keeps its own behaviour; only the empty
// space navigates.
const open = (event) => {
if (event.target.closest('a, button, input, select, textarea, label')) return;
window.location.hash = target.replace(/^#/, '');
};
line.addEventListener('click', open);
line.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
open(event);
}
});
}
return line;
}),
), ),
), ),
); );
@@ -128,11 +146,40 @@ export function table(columns, rows, { empty = 'Rien à afficher pour le moment.
export const spinner = (label = 'Chargement…') => export const spinner = (label = 'Chargement…') =>
h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label })); h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label }));
export const errorBox = (message, { retry } = {}) => /**
* A `undefined is not a function` reaching the screen almost always means the
* page and the API disagree on the shape of the data — which reads as a broken
* feature unless the box says otherwise.
*/
const looksLikeVersionMismatch = (message) =>
/Cannot read propert|undefined is not|is not a function|of undefined/i.test(String(message));
/**
* `error` carries the stack; `message` alone leaves nobody able to say where it
* came from. Showing it on the page matters for a self-hosted panel, where
* opening the developer console is not always an option.
*/
export const errorBox = (message, { retry, error = null } = {}) =>
h( h(
'div', 'div',
{ class: 'notice notice-error' }, { class: 'notice notice-error' },
h('p', { text: message }), h(
'div',
{},
h('p', { text: message }),
looksLikeVersionMismatch(message) &&
h('p', {
class: 'muted',
text: 'Cette erreur vient en général d’une interface plus ancienne que l’API : recharge avec Ctrl+Shift+R, et si elle persiste, re-téléverse le dossier src/web/public.',
}),
error?.stack &&
h(
'details',
{},
h('summary', { text: 'Détails techniques' }),
h('pre', {}, h('code', { text: error.stack })),
),
),
retry && button('Réessayer', retry, { tone: 'ghost' }), retry && button('Réessayer', retry, { tone: 'ghost' }),
); );
@@ -222,7 +269,9 @@ export async function renderAsync(host, load, build) {
const data = await load(); const data = await load();
mount(host, await build(data)); mount(host, await build(data));
} catch (error) { } catch (error) {
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build) })); // Swallowing the stack leaves a failure impossible to place.
console.error('[fws] échec du rendu', error);
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build), error }));
} }
return host; return host;
} }
+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

+545 -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);
@@ -534,6 +535,14 @@ pre code {
.table tbody tr:hover { .table tbody tr:hover {
background: color-mix(in srgb, var(--blue) 6%, transparent); background: color-mix(in srgb, var(--blue) 6%, transparent);
} }
.table tbody tr.row-link {
cursor: pointer;
}
.table tbody tr.row-link:focus-visible {
outline: 2px solid var(--blue);
outline-offset: -2px;
}
.num { .num {
text-align: right; text-align: right;
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
@@ -690,6 +699,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;
@@ -753,6 +771,73 @@ details > *:last-child {
margin-bottom: 0; margin-bottom: 0;
} }
/* --- Kanban --------------------------------------------------------------- */
.kboard {
display: flex;
gap: 0.8rem;
align-items: flex-start;
overflow-x: auto;
padding-bottom: 0.6rem;
}
.kcolumn {
flex: 0 0 280px;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.7rem;
display: flex;
flex-direction: column;
gap: 0.55rem;
min-height: 8rem;
}
.kcolumn > header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
font-size: 0.9rem;
}
/* Only the border moves: a background change under a dragged card flickers. */
.kcolumn-target {
border-color: var(--blue);
box-shadow: inset 0 0 0 1px var(--blue);
}
.kcolumn-over > header .muted {
color: var(--amber);
font-weight: 700;
}
.kcolumn-cards {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-height: 2.5rem;
}
.kcard {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.6rem 0.7rem;
cursor: grab;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.kcard:hover {
border-color: var(--blue);
}
.kcard h4 {
font-size: 0.88rem;
font-weight: 600;
}
.kcard.dragging {
opacity: 0.4;
cursor: grabbing;
}
/* --- Simple / advanced mode ---------------------------------------------- */ /* --- Simple / advanced mode ---------------------------------------------- */
body[data-mode='simple'] .advanced-only { body[data-mode='simple'] .advanced-only {
@@ -777,7 +862,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 +939,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 +1029,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;
@@ -979,6 +1079,425 @@ body[data-mode='simple'] .advanced-only {
border-bottom-color: var(--blue); border-bottom-color: var(--blue);
} }
/* --- My tasks ------------------------------------------------------------- */
.task-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.task {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.55rem 0.2rem;
border-bottom: 1px solid var(--border);
}
.task:last-child {
border-bottom: none;
}
.task-done .task-title {
text-decoration: line-through;
color: var(--text-muted);
}
.task-check {
flex: none;
width: 1.35rem;
height: 1.35rem;
border-radius: 50%;
border: 2px solid var(--border);
background: none;
color: var(--green);
font-size: 0.8rem;
line-height: 1;
cursor: pointer;
}
.task-check:hover:not(:disabled) {
border-color: var(--green);
}
.task-check:disabled {
cursor: default;
opacity: 0.7;
}
.task-body {
flex: 1;
min-width: 0;
}
.task-title {
display: block;
color: var(--text);
font-weight: 600;
font-size: 0.94rem;
}
.task-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
margin-top: 0.15rem;
}
.task-issue {
font-size: 0.78rem;
color: var(--gitea);
}
.task-due {
flex: none;
font-size: 0.8rem;
color: var(--text-muted);
white-space: nowrap;
}
.task-due-late {
color: var(--red);
font-weight: 600;
}
.task-archive {
padding: 0.8rem 1.1rem;
}
.task-archive summary {
cursor: pointer;
font-weight: 600;
font-size: 0.92rem;
}
.task-picker {
display: inline-flex;
}
.nav-count {
margin-left: auto;
min-width: 1.4rem;
text-align: center;
font-size: 0.72rem;
font-weight: 700;
border-radius: 999px;
padding: 0.05rem 0.35rem;
background: var(--surface);
color: var(--text-muted);
}
.nav-count[data-tone='late'] {
background: color-mix(in srgb, var(--red) 24%, transparent);
color: var(--red);
}
/* Anchored near the top rather than centred: the list grows downwards, and a
dialog that re-centres itself on every keystroke is unusable. */
/* --- Command palette ------------------------------------------------------ */
.nav-search {
display: flex;
align-items: center;
gap: 0.6rem;
width: 100%;
font: inherit;
font-size: 0.88rem;
text-align: left;
color: var(--text-muted);
background: var(--bg-sunken);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.45rem 0.65rem;
margin-bottom: 0.4rem;
cursor: pointer;
}
.nav-search:hover {
border-color: var(--blue);
color: var(--text);
}
.nav-search kbd {
margin-left: auto;
font-family: var(--mono);
font-size: 0.7rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
.palette-overlay {
align-items: start;
padding-top: min(14vh, 8rem);
}
.palette {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
width: min(640px, 100%);
max-height: 70vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.palette-head {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.7rem 0.9rem;
border-bottom: 1px solid var(--border);
}
.palette-prompt {
color: var(--blue);
font-size: 1.1rem;
}
.palette-input {
flex: 1;
font: inherit;
font-size: 1rem;
background: none;
border: none;
color: var(--text);
outline: none;
}
.palette-input::-webkit-search-cancel-button {
display: none;
}
.palette-list {
overflow-y: auto;
padding: 0.35rem;
}
.palette-group {
padding: 0.55rem 0.6rem 0.25rem;
font-size: 0.68rem;
letter-spacing: 0.09em;
text-transform: uppercase;
color: var(--text-muted);
}
.palette-item {
display: flex;
align-items: center;
gap: 0.7rem;
width: 100%;
font: inherit;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--text);
padding: 0.45rem 0.6rem;
cursor: pointer;
}
.palette-item.active {
background: color-mix(in srgb, var(--blue) 16%, transparent);
}
.palette-icon {
width: 1.3rem;
text-align: center;
color: var(--text-muted);
}
.palette-text {
display: flex;
flex-direction: column;
min-width: 0;
}
.palette-text strong {
font-weight: 600;
font-size: 0.92rem;
}
.palette-text span,
.palette-text strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.palette-badge {
margin-left: auto;
flex: none;
font-size: 0.7rem;
color: var(--text-muted);
background: var(--bg-sunken);
border-radius: 999px;
padding: 0.05rem 0.45rem;
}
.palette-external {
flex: none;
color: var(--text-muted);
font-size: 0.8rem;
}
.palette-empty {
padding: 1.2rem 0.6rem;
text-align: center;
color: var(--text-muted);
}
.palette-foot {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: center;
padding: 0.5rem 0.9rem;
border-top: 1px solid var(--border);
font-size: 0.76rem;
color: var(--text-muted);
}
.palette-hint {
min-width: 0;
}
/* --- Public status page --------------------------------------------------- */
.status-body {
background: var(--bg);
}
.status-page {
max-width: 820px;
margin: 0 auto;
padding: 2rem 1rem 3rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.status-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.status-brand {
display: flex;
align-items: center;
gap: 0.6rem;
color: var(--text);
}
.status-brand:hover {
text-decoration: none;
}
.status-brand strong {
display: block;
font-size: 1rem;
}
.status-brand span {
font-size: 0.8rem;
color: var(--text-muted);
}
.status-muted {
color: var(--text-muted);
font-size: 0.84rem;
}
.status-banner {
border: 1px solid var(--border);
border-left: 4px solid var(--text-muted);
border-radius: var(--radius);
background: var(--bg-elevated);
padding: 1.2rem 1.4rem;
}
.status-banner h1 {
font-size: 1.35rem;
margin-bottom: 0.3rem;
}
.status-banner p {
color: var(--text-muted);
margin: 0;
}
.status-banner-ok {
border-left-color: var(--green);
}
.status-banner-busy {
border-left-color: var(--amber);
}
.status-banner-down {
border-left-color: var(--red);
}
.status-section h2 {
margin-bottom: 0.7rem;
}
.status-tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 0.8rem;
}
.status-tile {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.8rem 0.9rem;
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.status-tile-label {
font-size: 0.74rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-muted);
}
.status-tile-value {
font-size: 1.15rem;
}
.status-tile-hint {
font-size: 0.76rem;
color: var(--text-muted);
}
.status-table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
.status-table th {
text-align: left;
font-size: 0.72rem;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--text-muted);
padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-table td {
padding: 0.55rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-pill {
display: inline-block;
font-size: 0.74rem;
font-weight: 600;
border-radius: 999px;
padding: 0.1rem 0.55rem;
background: var(--surface);
color: var(--text-muted);
}
.status-pill-ok {
background: color-mix(in srgb, var(--green) 20%, transparent);
color: var(--green);
}
.status-pill-busy {
background: color-mix(in srgb, var(--amber) 22%, transparent);
color: var(--amber);
}
.status-pill-down {
background: color-mix(in srgb, var(--red) 20%, transparent);
color: var(--red);
}
.status-releases {
list-style: none;
margin: 0;
padding: 0;
}
.status-releases li {
display: flex;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
padding: 0.5rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-releases li:last-child {
border-bottom: none;
}
.status-empty {
color: var(--text-muted);
font-size: 0.9rem;
padding: 0.6rem;
}
.status-generated {
margin: 0;
}
.status-footer {
border-top: 1px solid var(--border);
padding-top: 1rem;
font-size: 0.85rem;
color: var(--text-muted);
}
@media (max-width: 900px) { @media (max-width: 900px) {
.shell { .shell {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@@ -999,4 +1518,15 @@ body[data-mode='simple'] .advanced-only {
flex-direction: row; flex-direction: row;
overflow-x: auto; overflow-x: auto;
} }
.palette-overlay {
padding-top: 6vh;
}
.status-page {
padding: 1.2rem 1rem 2rem;
}
.status-table {
font-size: 0.82rem;
}
} }
+45 -9
View File
@@ -4,6 +4,7 @@ import {
badge, badge,
button, button,
card, card,
confirmAction,
field, field,
grid, grid,
input, input,
@@ -32,11 +33,13 @@ const DURATIONS = [
{ value: String(7 * 24 * 60 * 60_000), label: '7 jours' }, { value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
]; ];
// Mirrors MODERATION_ACTIONS in `src/config/constants.js`, emoji included: the
// panel must not be the one place where a mute reads like a kick.
const MODERATION_ACTIONS = [ const MODERATION_ACTIONS = [
{ value: 'warn', label: 'Avertissement' }, { value: 'warn', label: '⚠️ Avertissement' },
{ value: 'mute', label: 'Exclusion temporaire' }, { value: 'mute', label: '🔇 Mise en sourdine' },
{ value: 'kick', label: 'Expulsion' }, { value: 'kick', label: '👢 Expulsion' },
{ value: 'ban', label: 'Bannissement' }, { value: 'ban', label: '🔨 Bannissement' },
]; ];
async function moderate(member, reload) { async function moderate(member, reload) {
@@ -163,9 +166,15 @@ async function announce(channels) {
toast(`Annonce publiée (${result.messageId}).`); toast(`Annonce publiée (${result.messageId}).`);
} }
function membersCard(guild, level) { function membersCard(guild, level, initialSearch = '') {
const host = h('div', { class: 'stack' }); const host = h('div', { class: 'stack' });
const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' }); // Pre-filled when the command palette sent us here for one member, so the
// link lands on that person rather than on the top of the roster.
const search = input({
type: 'search',
placeholder: 'Nom, pseudo ou identifiant…',
value: initialSearch,
});
const load = () => const load = () =>
renderAsync( renderAsync(
@@ -304,6 +313,9 @@ function notificationsCard(guild, level) {
); );
} }
/** `#/discord?member=nom` — where the command palette points a member result. */
const memberQuery = () => new URLSearchParams(window.location.hash.split('?')[1] ?? '').get('member') ?? '';
export async function render(host, { state }) { export async function render(host, { state }) {
const level = state.me.accessLevel; const level = state.me.accessLevel;
mount(host, spinner()); mount(host, spinner());
@@ -355,7 +367,7 @@ export async function render(host, { state }) {
), ),
), ),
membersCard(guild, level), membersCard(guild, level, memberQuery()),
card( card(
'Rôles', 'Rôles',
@@ -397,8 +409,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 -2
View File
@@ -164,7 +164,7 @@ export function render(host, { state }) {
card( card(
'Dépôts', 'Dépôts',
{ subtitle: 'Clique sur un dépôt pour le gérer en détail.' }, { subtitle: 'Clique sur une ligne pour gérer le dépôt en détail.' },
table( table(
[ [
{ {
@@ -207,7 +207,10 @@ export function render(host, { state }) {
}, },
], ],
data.repositories, data.repositories,
{ empty: 'Aucun dépôt dans cette organisation.' }, {
empty: 'Aucun dépôt dans cette organisation.',
rowHref: (repository) => `#/repos/${repository.fullName}`,
},
), ),
), ),
+1
View File
@@ -96,6 +96,7 @@ function giteaCard(gitea) {
}, },
], ],
gitea.repositories, gitea.repositories,
{ rowHref: (repository) => `#/repos/${repository.fullName}` },
), ),
); );
} }
+481
View File
@@ -0,0 +1,481 @@
import { api } from '../core/api.js';
import { formatRelative, h, mount } from '../core/dom.js';
import { autoRefresh } from '../core/live.js';
import {
badge,
button,
card,
confirmDangerous,
field,
input,
modal,
notice,
renderAsync,
select,
spinner,
table,
textarea,
toast,
toggle,
} from '../core/ui.js';
/** Kanban boards: one per repository, one for the organization (M18). */
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
const overdue = (dueAt) => dueAt && new Date(`${dueAt}Z`) < new Date();
// --- Board list --------------------------------------------------------------
function renderList(host, state) {
const reload = () => renderList(host, state);
return renderAsync(
host,
async () => {
const [projects, repositories] = await Promise.all([
api.get('/api/projects'),
api.get('/api/repositories').catch(() => ({ repositories: [] })),
]);
return { ...projects, repositories: repositories.repositories ?? [] };
},
(data) => {
const taken = new Set(data.boards.map((entry) => entry.repository).filter(Boolean));
const available = data.repositories.filter((entry) => !taken.has(entry.fullName));
return h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('h1', { text: 'Projets' }),
h('p', {
class: 'muted',
text: 'Un tableau par dépôt, plus un pour l’organisation. Les cartes peuvent pointer vers une issue Gitea.',
}),
),
h(
'div',
{ class: 'row' },
!data.orgBoard &&
button('Tableau de l’organisation', () => createBoard({ scope: 'org' }, reload), {
tone: 'primary',
}),
available.length > 0 &&
button('Tableau de dépôt', () => createBoard({ scope: 'repo', available }, reload), {
tone: available.length > 0 && data.orgBoard ? 'primary' : 'ghost',
}),
),
),
data.boards.length === 0 &&
notice(
'Aucun tableau pour l’instant. Commence par celui de l’organisation, puis ajoute ceux des dépôts.',
'info',
),
card(
'Tableaux',
{ subtitle: `${data.boards.length} tableau(x)` },
table(
[
{
label: 'Tableau',
render: (entry) =>
h(
'div',
{},
h('strong', { text: entry.name }),
h('div', {
class: 'muted',
text: entry.scope === 'org' ? 'Organisation' : entry.repository,
}),
),
},
{
label: 'Portée',
render: (entry) =>
entry.scope === 'org' ? badge('Organisation', 'info') : badge('Dépôt', 'neutral'),
},
{ label: 'Colonnes', className: 'num', key: 'columns' },
{ label: 'Cartes', className: 'num', key: 'cards' },
{
label: 'Modifié',
className: 'nowrap',
render: (entry) => formatRelative(entry.updatedAt),
},
],
data.boards,
{
empty: 'Aucun tableau.',
rowHref: (entry) => `#/projects/${entry.id}`,
},
),
),
);
},
);
}
async function createBoard({ scope, available = [] }, reload) {
const name = input({ placeholder: scope === 'org' ? 'Organisation FWS' : 'Nom du tableau' });
const repository =
scope === 'repo'
? select(
available.map((entry) => ({ value: entry.fullName, label: entry.fullName })),
{},
)
: null;
const description = input({ placeholder: 'À quoi sert ce tableau ?' });
const confirmed = await modal(
scope === 'org' ? 'Tableau de l’organisation' : 'Nouveau tableau de dépôt',
() => ({
node: h(
'div',
{ class: 'stack' },
repository && field('Dépôt', repository),
field('Nom', name, { help: 'Laisse vide pour reprendre le nom du dépôt.' }),
field('Description', description),
h('p', {
class: 'muted',
text: 'Les colonnes À faire, En cours, En revue et Terminé sont créées automatiquement.',
}),
),
submit: () => scope === 'org' || Boolean(repository?.value),
}),
{ confirmLabel: 'Créer', tone: 'primary' },
);
if (!confirmed) return;
await api.post('/api/projects', {
scope,
repository: repository?.value,
name: name.value.trim(),
description: description.value.trim(),
});
toast('Tableau créé.');
reload();
}
// --- Board -------------------------------------------------------------------
function cardNode(entry, issues, board, reload) {
const issue = entry.issueRef ? issues[entry.issueRef] : null;
const node = h(
'article',
{ class: 'kcard', draggable: 'true', dataset: { card: String(entry.id) } },
h('h4', { text: entry.title }),
h(
'div',
{ class: 'row' },
entry.labels.map((label) => badge(label, 'neutral')),
issue &&
badge(
`${entry.issueRef} · ${issue.state === 'open' ? 'ouverte' : 'fermée'}`,
issue.state === 'open' ? 'success' : 'neutral',
),
!issue && entry.issueRef && badge(entry.issueRef, 'neutral'),
entry.dueAt && badge(formatRelative(entry.dueAt), overdue(entry.dueAt) ? 'danger' : 'warning'),
),
entry.assigneeId && h('div', { class: 'muted', text: `Assignée à ${entry.assigneeId}` }),
);
node.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', String(entry.id));
event.dataTransfer.effectAllowed = 'move';
node.classList.add('dragging');
});
node.addEventListener('dragend', () => node.classList.remove('dragging'));
node.addEventListener('click', () => editCard(board, entry, reload));
return node;
}
function columnNode(column, issues, board, reload) {
const count = column.cards.length;
const over = column.wipLimit > 0 && count > column.wipLimit;
const list = h(
'div',
{ class: 'kcolumn-cards' },
column.cards.map((entry) => cardNode(entry, issues, board, reload)),
);
const node = h(
'section',
{ class: over ? 'kcolumn kcolumn-over' : 'kcolumn', dataset: { column: String(column.id) } },
h(
'header',
{},
h('strong', { text: column.name }),
h(
'span',
{ class: 'muted' },
h('span', { text: column.wipLimit > 0 ? `${count} / ${column.wipLimit}` : String(count) }),
),
),
list,
button('+ Carte', () => editCard(board, { columnId: column.id }, reload), { tone: 'ghost' }),
);
// Dropping anywhere on the column appends; the API renumbers the rest.
node.addEventListener('dragover', (event) => {
event.preventDefault();
node.classList.add('kcolumn-target');
});
node.addEventListener('dragleave', () => node.classList.remove('kcolumn-target'));
node.addEventListener('drop', async (event) => {
event.preventDefault();
node.classList.remove('kcolumn-target');
const cardId = event.dataTransfer.getData('text/plain');
if (!cardId) return;
const result = await api.post(`/api/projects/${board.id}/cards/${cardId}/move`, {
columnId: column.id,
position: column.cards.length,
});
if (result.overloaded) toast(`« ${column.name} » dépasse sa limite de ${column.wipLimit}.`, 'info');
reload();
});
return node;
}
async function editCard(board, entry, reload) {
const existing = Boolean(entry.id);
const title = input({ value: entry.title ?? '', placeholder: 'Ce qu’il y a à faire' });
const body = textarea({ value: entry.body ?? '', placeholder: 'Contexte, critères d’acceptation…' });
const assignee = input({ value: entry.assigneeId ?? '', placeholder: 'Identifiant Discord (facultatif)' });
const issueRef = input({ value: entry.issueRef ?? '', placeholder: 'FWS/FWS-Arch#12 (facultatif)' });
const labels = input({ value: (entry.labels ?? []).join(', '), placeholder: 'bug, urgent' });
const dueAt = input({ type: 'date', value: (entry.dueAt ?? '').slice(0, 10) });
const confirmed = await modal(
existing ? 'Modifier la carte' : 'Nouvelle carte',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Titre', title),
field('Description', body),
field('Assignée à', assignee, { help: 'Identifiant Discord du membre qui la porte.' }),
field('Issue liée', issueRef, {
help: 'Format `organisation/depot#12`. Son état s’affiche sur la carte.',
}),
field('Étiquettes', labels, { help: 'Séparées par des virgules.' }),
field('Échéance', dueAt),
),
submit: () => title.value.trim().length >= 2,
}),
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
);
if (!confirmed) return;
const payload = {
title: title.value.trim(),
body: body.value,
assigneeId: assignee.value.trim(),
issueRef: issueRef.value.trim(),
labels: labels.value
.split(',')
.map((label) => label.trim())
.filter(Boolean),
dueAt: dueAt.value || '',
};
try {
if (existing) await api.patch(`/api/projects/${board.id}/cards/${entry.id}`, payload);
else await api.post(`/api/projects/${board.id}/cards`, { ...payload, columnId: entry.columnId });
toast(existing ? 'Carte enregistrée.' : 'Carte créée.');
reload();
} catch (error) {
toast(error.message, 'error');
}
}
async function renderBoard(host, state, id) {
const level = state.me.accessLevel;
const reload = () => renderBoard(host, state, id);
autoRefresh(reload, { topics: ['mutation'], minIntervalMs: 3000 });
mount(host, spinner());
let board;
try {
board = await api.get(`/api/projects/${id}`);
} catch (error) {
mount(host, notice(error.message, 'error'));
return;
}
const total = board.columns.reduce((sum, column) => sum + column.cards.length, 0);
const done = board.columns
.filter((column) => column.isDone)
.reduce((sum, column) => sum + column.cards.length, 0);
mount(
host,
h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('p', { class: 'muted' }, h('a', { href: '#/projects', text: '← Tous les tableaux' })),
h('h1', { text: board.name }),
h('p', {
class: 'muted',
text: board.description || (board.repository ?? 'Tableau de l’organisation'),
}),
h(
'div',
{ class: 'row' },
badge(`${total} carte(s)`, 'neutral'),
badge(`${done} terminée(s)`, done > 0 ? 'success' : 'neutral'),
),
),
h(
'div',
{ class: 'row' },
button('Importer depuis Gitea', () => importIssues(board, reload), { tone: 'ghost' }),
button('Colonne', () => addColumn(board, reload), { tone: 'ghost' }),
level >= LEVELS.OWNER &&
button(
'Supprimer',
async () => {
if (
!(await confirmDangerous(
'Supprimer le tableau',
`« ${board.name} » et toutes ses cartes seront perdus.`,
board.name,
))
) {
return;
}
await api.delete(`/api/projects/${board.id}`, { confirm: board.name });
toast('Tableau supprimé.');
window.location.hash = '#/projects';
},
{ tone: 'danger' },
),
),
),
h(
'div',
{ class: 'kboard' },
board.columns.map((column) => columnNode(column, board.issues ?? {}, board, reload)),
),
),
);
}
/**
* Pulls Gitea issues onto the board.
*
* Offered on every board, not only on a repository one: the organization board
* is exactly where issues from several repositories belong together.
*/
async function importIssues(board, reload) {
const { repositories } = await api.get('/api/repositories').catch(() => ({ repositories: [] }));
const repository =
repositories.length > 0
? select(
repositories.map((entry) => ({ value: entry.fullName, label: entry.fullName })),
{ value: board.repository ?? repositories[0]?.fullName },
)
: input({ value: board.repository ?? '', placeholder: 'FWS/FWS-Arch' });
const column = select(
board.columns.map((entry) => ({ value: String(entry.id), label: entry.name })),
{ value: String((board.columns.find((entry) => !entry.isDone) ?? board.columns[0])?.id) },
);
let closedToo = false;
const confirmed = await modal(
'Importer depuis Gitea',
() => ({
node: h(
'div',
{ class: 'stack' },
repositories.length === 0 &&
notice(
'La liste des dépôts est indisponible — saisis le dépôt à la main, au format `organisation/depot`.',
'warning',
),
field('Dépôt', repository),
field('Colonne d’arrivée', column),
toggle(false, (checked) => (closedToo = checked), 'Inclure aussi les issues fermées'),
h('p', {
class: 'muted',
text: 'Une issue déjà présente sur le tableau est ignorée : tu peux relancer l’import sans créer de doublon.',
}),
),
submit: () => repository.value.trim() !== '',
}),
{ confirmLabel: 'Importer', tone: 'primary' },
);
if (!confirmed) return;
try {
const result = await api.post(`/api/projects/${board.id}/import`, {
repository: repository.value.trim(),
columnId: Number(column.value),
state: closedToo ? 'all' : 'open',
});
toast(
result.imported === 0
? `Rien à importer : les ${result.found} issue(s) de ${result.repository} sont déjà sur le tableau.`
: `${result.imported} carte(s) créée(s) dans « ${result.column} », ${result.skipped} déjà présente(s).`,
result.imported === 0 ? 'info' : 'success',
);
reload();
} catch (error) {
toast(error.message, 'error');
}
}
async function addColumn(board, reload) {
const name = input({ placeholder: 'Nom de la colonne' });
const wipLimit = input({ type: 'number', value: 0, min: 0 });
let isDone = false;
const confirmed = await modal(
'Nouvelle colonne',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Nom', name),
field('Limite de cartes', wipLimit, { help: '0 = pas de limite. Au-delà, la colonne est signalée.' }),
toggle(false, (checked) => (isDone = checked), 'Les cartes déposées ici sont terminées'),
),
submit: () => name.value.trim() !== '',
}),
{ confirmLabel: 'Ajouter', tone: 'primary' },
);
if (!confirmed) return;
await api.post(`/api/projects/${board.id}/columns`, {
name: name.value.trim(),
wipLimit: Number(wipLimit.value) || 0,
isDone,
});
toast('Colonne ajoutée.');
reload();
}
export function render(host, { params, state }) {
if (params.length >= 1) return renderBoard(host, state, params[0]);
return renderList(host, state);
}
+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',
+149 -47
View File
@@ -17,6 +17,7 @@ import {
stat, stat,
table, table,
toast, toast,
textarea,
toggle, toggle,
} from '../core/ui.js'; } from '../core/ui.js';
@@ -33,47 +34,136 @@ 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' && Array.isArray(setting.options)) {
'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') { // Markdown is a long text: a single-line input would hide what is written.
return h( if (setting.type === 'markdown') {
const editor = textarea({
value: value ?? '',
rows: 12,
maxlength: setting.maxLength,
placeholder: '## Règlement\n\n1. …\n2. …',
});
return field(
setting.label,
h(
'div',
{ class: 'stack' },
editor,
h(
'div', 'div',
{}, { class: 'row' },
toggle(Boolean(data.values[setting.key]), apply, setting.label), button('Enregistrer', () => apply(editor.value), { tone: 'primary' }),
h('div', { class: 'field-help', text: setting.help }),
);
}
return field(
setting.label,
select(
setting.options.map((option) => ({ value: option, label: option })),
{ value: data.values[setting.key], onChange: (event) => apply(event.target.value) },
), ),
{ help: setting.help }, ),
{ help: setting.help },
);
}
const control = input({
value: value ?? '',
type: setting.type === 'int' ? 'number' : 'text',
min: setting.min,
max: setting.max,
maxlength: setting.maxLength,
placeholder: String(setting.default ?? ''),
});
// Text fields save on blur rather than on every keystroke.
const commit = () => apply(setting.type === 'int' ? Number(control.value) : control.value);
control.addEventListener('change', commit);
control.addEventListener('keydown', (event) => {
if (event.key === 'Enter') control.blur();
});
return field(setting.label, control, { help: setting.help });
}
function behaviourCard(data, level, reload) {
const editable = level >= LEVELS.DEV;
const schema = Array.isArray(data.schema) ? data.schema : [];
const values = data.values ?? {};
// Falling back to one section keeps the page useful against an API that does
// not group its settings, rather than rendering nothing at all.
const sections = Array.isArray(data.sections)
? data.sections
: [{ id: null, title: 'Comportement du bot', summary: null }];
return h(
'div',
{ class: 'stack' },
...sections.map((section) => {
const settings = section.id ? schema.filter((setting) => setting.section === section.id) : schema;
if (settings.length === 0) return null;
return card(
section.title,
{ subtitle: section.summary },
...settings.map((setting) => {
const value = 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 {
// The rules are a message on Discord, not a stored value: saving
// them has to publish them.
if (setting.key === 'rules.markdown') {
const published = await api.post('/api/discord/rules', { markdown: next });
values[setting.key] = next;
toast(
published.edited
? 'Règlement mis à jour dans le salon des règles.'
: 'Règlement publié et épinglé dans le salon des règles.',
published.pinned ? 'success' : 'info',
);
return;
}
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
toast(`« ${setting.label} » enregistré.`);
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' }),
); );
} }
@@ -87,7 +177,13 @@ const testButton = (service, label) =>
{ tone: 'ghost' }, { tone: 'ghost' },
); );
function connectionsCard(data) { function connectionsCard(raw) {
const data = {
discord: raw.discord ?? {},
gitea: raw.gitea ?? {},
webhook: raw.webhook ?? {},
web: raw.web ?? {},
};
return h( return h(
'div', 'div',
{ class: 'stack' }, { class: 'stack' },
@@ -105,13 +201,13 @@ function connectionsCard(data) {
h( h(
'div', 'div',
{ class: 'advanced-only' }, { class: 'advanced-only' },
keyValue(Object.entries(data.discord.roles).map(([label, value]) => ({ label, value }))), keyValue(Object.entries(data.discord.roles ?? {}).map(([label, value]) => ({ label, value }))),
), ),
h('h3', { class: 'advanced-only', text: 'Salons' }), h('h3', { class: 'advanced-only', text: 'Salons' }),
h( h(
'div', 'div',
{ class: 'advanced-only' }, { class: 'advanced-only' },
keyValue(Object.entries(data.discord.channels).map(([label, value]) => ({ label, value }))), keyValue(Object.entries(data.discord.channels ?? {}).map(([label, value]) => ({ label, value }))),
), ),
), ),
@@ -353,14 +449,15 @@ function tokensCard(reload) {
} }
function maintenanceCard(data) { function maintenanceCard(data) {
const runtime = data.runtime ?? {};
return card( return card(
'Maintenance', 'Maintenance',
{ subtitle: `Base : ${data.runtime.databasePath}` }, { subtitle: `Base : ${runtime.databasePath ?? '—'}` },
grid( grid(
stat('Environnement', data.runtime.nodeEnv), stat('Environnement', runtime.nodeEnv),
stat('Niveau de log', data.runtime.logLevel), stat('Niveau de log', runtime.logLevel),
stat('Rétention', `${data.runtime.logRetentionDays} jours`), stat('Rétention', `${runtime.logRetentionDays ?? '—'} jours`),
stat('PID', data.runtime.pid), stat('PID', runtime.pid),
), ),
h( h(
'div', 'div',
@@ -381,7 +478,7 @@ function maintenanceCard(data) {
}, },
{ tone: 'ghost' }, { tone: 'ghost' },
), ),
data.web.allowRestart && data.web?.allowRestart &&
button( button(
'Redémarrer le bot', 'Redémarrer le bot',
async () => { async () => {
@@ -397,12 +494,13 @@ function maintenanceCard(data) {
{ tone: 'danger' }, { tone: 'danger' },
), ),
), ),
!data.web.allowRestart && !data.web?.allowRestart &&
h('p', { class: 'muted', text: 'Le redémarrage depuis le site est désactivé (`WEB_ALLOW_RESTART`).' }), h('p', { class: 'muted', text: 'Le redémarrage depuis le site est désactivé (`WEB_ALLOW_RESTART`).' }),
); );
} }
function referenceCard(data) { function referenceCard(data) {
const reference = data.reference ?? {};
return card( return card(
'Référence', 'Référence',
{ advanced: true, subtitle: 'Ce que le bot connaît, pour se repérer.' }, { advanced: true, subtitle: 'Ce que le bot connaît, pour se repérer.' },
@@ -413,7 +511,7 @@ function referenceCard(data) {
{ label: 'Valeur', className: 'num', key: 'value' }, { label: 'Valeur', className: 'num', key: 'value' },
{ label: 'Libellé Discord', key: 'label' }, { label: 'Libellé Discord', key: 'label' },
], ],
data.reference.accessLevels, reference.accessLevels ?? [],
), ),
h('h3', { text: 'Catégories de tickets' }), h('h3', { text: 'Catégories de tickets' }),
table( table(
@@ -422,13 +520,13 @@ function referenceCard(data) {
{ label: 'Libellé', key: 'label' }, { label: 'Libellé', key: 'label' },
{ label: 'Visible par', render: (category) => category.scope.join(', ') }, { label: 'Visible par', render: (category) => category.scope.join(', ') },
], ],
data.reference.ticketCategories, reference.ticketCategories ?? [],
), ),
h('h3', { text: 'Types de notification' }), h('h3', { text: 'Types de notification' }),
h( h(
'div', 'div',
{ class: 'row' }, { class: 'row' },
data.reference.notificationTypes.map((type) => badge(type, 'info')), (reference.notificationTypes ?? []).map((type) => badge(type, 'info')),
), ),
); );
} }
@@ -459,7 +557,11 @@ export function render(host, { state }) {
}), }),
), ),
level >= LEVELS.OWNER && level >= LEVELS.OWNER &&
h('a', { class: 'btn btn-primary', href: '#/setup', text: 'Assistant de configuration .env' }), h('a', {
class: 'btn btn-primary',
href: '#/setup',
text: 'Assistant de configuration .env',
}),
), ),
level >= LEVELS.OWNER && level >= LEVELS.OWNER &&
+249
View File
@@ -0,0 +1,249 @@
import { api } from '../core/api.js';
import { formatRelative, h, mount } from '../core/dom.js';
import { autoRefresh } from '../core/live.js';
import { badge, card, notice, renderAsync, select, stat, toast } from '../core/ui.js';
/**
* « Mes tâches » — every card one member carries, across every board (M19).
*
* A board answers « where does the work stand ». Nobody opens a dashboard to
* ask that first: they ask what is on them today, and once the work is spread
* over several boards no single board can say.
*/
const today = () => new Date().toISOString().slice(0, 10);
const day = (value) => (value ? String(value).slice(0, 10) : null);
const plus = (days) => {
const date = new Date();
date.setDate(date.getDate() + days);
return date.toISOString().slice(0, 10);
};
/**
* Buckets, in the order someone wants to be told about them: what is late,
* what is due, then everything else. A card with no date is not urgent but is
* not invisible either — it sits at the bottom rather than nowhere.
*/
function bucketOf(task) {
if (task.isDone) return 'done';
const due = day(task.dueAt);
if (!due) return 'undated';
if (due < today()) return 'overdue';
if (due === today()) return 'today';
return due <= plus(7) ? 'week' : 'later';
}
const BUCKETS = [
{ key: 'overdue', title: 'En retard' },
{ key: 'today', title: 'Pour aujourd’hui' },
{ key: 'week', title: 'Cette semaine' },
{ key: 'later', title: 'Plus tard' },
{ key: 'undated', title: 'Sans échéance' },
];
/** Member names, asked once: the picker must not cost a roster fetch per render. */
let memberNames = null;
async function names() {
if (memberNames) return memberNames;
const data = await api.get('/api/discord/members', { limit: 200 }).catch(() => null);
memberNames = new Map((data?.members ?? []).map((member) => [member.id, member.displayName]));
return memberNames;
}
async function finish(task, reload) {
if (!task.doneColumnId) {
toast('Ce tableau n’a pas de colonne « terminé ».', 'error');
return;
}
await api.post(`/api/projects/${task.boardId}/cards/${task.id}/move`, {
columnId: task.doneColumnId,
position: 0,
});
toast(`« ${task.title} » est terminée.`);
// The shell owns the sidebar counter; it has no reason to know this view.
document.dispatchEvent(new CustomEvent('fws:tasks-changed'));
reload();
}
function taskRow(task, issues, reload) {
const issue = task.issueRef ? issues[task.issueRef] : null;
const due = day(task.dueAt);
const late = !task.isDone && due && due < today();
return h(
'li',
{ class: task.isDone ? 'task task-done' : 'task', dataset: { bucket: bucketOf(task) } },
h(
'button',
{
class: 'task-check',
type: 'button',
title: task.isDone ? 'Déjà terminée' : 'Marquer comme terminée',
disabled: task.isDone || !task.doneColumnId,
onClick: () => finish(task, reload),
},
h('span', { text: task.isDone ? '✓' : '' }),
),
h(
'div',
{ class: 'task-body' },
h(
'a',
{ class: 'task-title', href: `#/projects/${task.boardId}`, title: 'Ouvrir le tableau' },
task.title,
),
h(
'div',
{ class: 'task-meta' },
h('span', { class: 'muted', text: task.boardName }),
badge(task.columnName, task.isDone ? 'success' : 'neutral'),
task.labels.map((label) => badge(label, 'info')),
issue &&
h(
'a',
{ href: issue.htmlUrl, target: '_blank', rel: 'noreferrer', class: 'task-issue' },
`${task.issueRef} · ${issue.state === 'closed' ? 'fermée' : 'ouverte'}`,
),
!issue && task.issueRef && h('span', { class: 'muted', text: task.issueRef }),
),
),
due &&
h(
'span',
{ class: late ? 'task-due task-due-late' : 'task-due', title: due },
formatRelative(`${due}T12:00:00Z`),
),
);
}
/**
* Returns its node right away and fills it once the names arrive: waiting on
* Discord would hold up the tasks, which are the point of the page.
*/
function picker(data, reload) {
if (data.assignees.length < 2) return null;
const host = h('span', { class: 'task-picker' });
const build = (resolved) =>
mount(
host,
select(
[
{ value: '', label: 'Moi' },
...data.assignees.map((entry) => ({
value: entry.assigneeId,
label: `${resolved.get(entry.assigneeId) ?? entry.assigneeId} (${entry.open})`,
})),
],
{
value: data.self ? '' : data.assigneeId,
'aria-label': 'Voir les tâches de',
onChange: (event) => reload(event.target.value),
},
),
);
if (memberNames) build(memberNames);
else names().then(build);
return host;
}
export function render(host) {
let assignee = '';
const load = () => api.get('/api/me/tasks', { assignee });
const reload = (next) => {
if (next !== undefined) assignee = next;
return draw();
};
const draw = () =>
renderAsync(host, load, (data) => {
const grouped = new Map(BUCKETS.map((bucket) => [bucket.key, []]));
const done = [];
for (const task of data.cards) {
const bucket = bucketOf(task);
if (bucket === 'done') done.push(task);
else grouped.get(bucket).push(task);
}
const owner = data.self ? 'toi' : (memberNames?.get(data.assigneeId) ?? `le membre ${data.assigneeId}`);
return h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('h1', { text: data.self ? 'Mes tâches' : 'Tâches assignées' }),
h('p', {
class: 'muted',
text: `Toutes les cartes assignées à ${owner}, tous tableaux confondus, la plus urgente en premier.`,
}),
),
h('div', { class: 'row' }, picker(data, reload)),
),
h(
'div',
{ class: 'grid' },
stat('À faire', data.counts.open, { tone: data.counts.open > 0 ? 'primary' : 'neutral' }),
stat('En retard', data.counts.overdue, {
tone: data.counts.overdue > 0 ? 'danger' : 'neutral',
}),
stat('Pour aujourd’hui', data.counts.dueToday, {
tone: data.counts.dueToday > 0 ? 'warning' : 'neutral',
}),
stat('Terminées', data.counts.done),
),
data.cards.length === 0 &&
notice(
data.self
? 'Rien ne t’est assigné. Ouvre un tableau et mets ton nom sur une carte pour la voir apparaître ici.'
: 'Aucune carte n’est assignée à ce membre.',
'info',
),
BUCKETS.map((bucket) => {
const tasks = grouped.get(bucket.key);
if (tasks.length === 0) return null;
return card(
bucket.title,
{ subtitle: `${tasks.length} carte(s)` },
h(
'ul',
{ class: 'task-list' },
tasks.map((task) => taskRow(task, data.issues, () => reload())),
),
);
}),
done.length > 0 &&
h(
'details',
{ class: 'card task-archive' },
h('summary', { text: `Terminées (${done.length})` }),
h(
'ul',
{ class: 'task-list' },
done.map((task) => taskRow(task, data.issues, () => reload())),
),
),
);
});
autoRefresh(() => draw(), { topics: ['projects', 'tick'] });
return draw();
}
+241
View File
@@ -0,0 +1,241 @@
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 || page.path }),
h('div', { class: 'muted', style: { fontFamily: 'var(--mono)' }, text: page.path }),
),
},
{ 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: page.path,
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.' },
),
),
);
},
);
}
+229
View File
@@ -0,0 +1,229 @@
/* 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-search {
margin: 0;
}
.wiki-index {
list-style: none;
margin: 0 0 1.4rem;
padding: 0;
}
.wiki-index li {
padding: 0.35rem 0;
border-bottom: 1px solid var(--border);
}
.wiki-index li:last-child {
border-bottom: none;
}
.wiki-footer {
margin-top: 3rem;
padding-top: 1rem;
border-top: 1px solid var(--border);
font-size: 0.8rem;
color: var(--text-muted);
}
.wiki-footer a {
color: var(--text-muted);
}
.wiki-footer a:hover {
color: var(--text);
}
.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;
}
}
+128 -5
View File
@@ -9,12 +9,73 @@ import { registerApiRoutes } from './api/index.js';
import { authenticate, assertSameOrigin } from './auth/session.js'; import { authenticate, assertSameOrigin } from './auth/session.js';
import { authorize } from './auth/guard.js'; 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, sendHtml, sendJson, sendStatic } from './http.js';
import { createRouter } from './router.js'; import { createRouter } from './router.js';
import { listPublished } from '../database/repositories/wiki-repository.js';
import { renderStatus } from './services/status-render.js';
import { statusSnapshot } from './services/status-service.js';
import { pagePath } from './services/wiki-seed.js';
import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js';
import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js';
/** HTTP server of the dashboard (M16-T01). */ /** HTTP server of the dashboard (M16-T01). */
const log = createLogger('web'); const log = createLogger('web');
/**
* The wiki address a path stands for: `''` for the index, a slug for a page,
* `null` when the path is not the wiki's business.
*/
function wikiSlug(pathname) {
const clean = pathname.replace(/\/+$/, '');
if (clean === '/wiki' || clean === '') return clean === '/wiki' ? '' : null;
if (clean.startsWith('/wiki/')) return decodeURIComponent(clean.slice('/wiki/'.length));
const root = clean.replace(/^\//, '');
return ROOT_PAGES.includes(root) ? root : null;
}
/** Answers with the finished HTML of a wiki page, or its index. */
function sendWiki(response, slug, term) {
let pages = [];
try {
pages = listPublished();
} catch (error) {
log.warn('Could not read the wiki pages', error);
}
const categories = [];
for (const page of pages) {
const entry = { ...page, path: pagePath(page.slug) };
let category = categories.find((item) => item.name === page.category);
if (!category) categories.push((category = { name: page.category, pages: [] }));
category.pages.push(entry);
}
const all = categories.flatMap((category) => category.pages);
if (slug === '') {
const needle = term.trim().toLowerCase();
const results =
needle.length >= 2
? all.filter((page) =>
[page.title, page.summary, page.content].some((field) =>
String(field ?? '')
.toLowerCase()
.includes(needle),
),
)
: null;
sendHtml(response, 200, renderIndex(categories, { term, results }));
return;
}
const page = all.find((entry) => entry.slug === slug);
if (!page) {
sendHtml(response, 404, renderNotFound(categories));
return;
}
sendHtml(response, 200, renderPage(page, categories));
}
const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public'); const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
/** Sliding window per client address, reset every minute. */ /** Sliding window per client address, reset every minute. */
@@ -71,9 +132,39 @@ 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 rendered here rather than in the browser: a terms page
// its shell so client-side routing works on a hard refresh. // that needs scripts to show its text reads as blank to anything that
const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' }); // does not run them, which includes whoever checks the link before
// approving an application.
const slug = wikiSlug(pathname);
if (slug !== null) {
sendWiki(response, slug, url.searchParams.get('q') ?? '');
return;
}
// Same reasoning for the status page, with one addition: it is read when
// something is wrong, which is the worst moment to need a working browser.
// Turned off, it answers 404 rather than falling through to the dashboard
// shell — « this address does not exist here » is the honest answer, and
// a shell served at /status only looks like a broken status page.
if (pathname.replace(/\/+$/, '') === '/status') {
if (!env.web.publicStatus) {
sendEmpty(response, 404);
return;
}
try {
sendHtml(response, 200, renderStatus(await statusSnapshot(context)));
} catch (error) {
log.error('Could not render the status page', error);
sendHtml(response, 503, '<!doctype html><title>État indisponible</title><p>État indisponible.');
}
return;
}
const served = await sendStatic(response, publicDir, pathname, {
fallback: 'index.html',
request,
});
if (!served) sendEmpty(response, 404); if (!served) sendEmpty(response, 404);
return; return;
} }
@@ -128,13 +219,45 @@ 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, () => {
const url = env.web.publicUrl || `http://${env.web.host}:${env.web.port}`; const url = env.web.publicUrl || `http://${env.web.host}:${env.web.port}`;
log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly }); log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly });
// Inside a container, binding a port that is not published succeeds and is
// still unreachable from outside, which looks exactly like a crash from the
// browser. Say it once, here, where the port is known.
if (env.web.host === '0.0.0.0') {
log.info(
`Le tableau de bord écoute sur le port ${env.web.port}. Dans un conteneur ou sur un panel, ` +
'ce port doit aussi faire partie des allocations publiées, sinon il reste injoignable de l’extérieur.',
);
}
});
server.on('error', (error) => {
const causes = {
EADDRINUSE: `le port ${env.web.port} est déjà pris par un autre processus`,
EACCES: `le port ${env.web.port} est interdit à ce processus (port privilégié, ou restreint par l’hôte)`,
EADDRNOTAVAIL: `l’adresse ${env.web.host} n’existe pas sur cette machine`,
};
const cause = causes[error.code] ?? error.message;
log.error(
`Le tableau de bord n'a pas pu démarrer sur ${env.web.host}:${env.web.port} — ${cause}. ` +
'Le bot continue sans le site : corrige `WEB_HOST` ou `WEB_PORT`, puis redémarre.',
error,
);
}); });
server.on('error', (error) => log.error('Dashboard server error', error));
// Open event streams would otherwise keep the server from closing. // Open event streams would otherwise keep the server from closing.
server.on('close', closeEventStreams); server.on('close', closeEventStreams);
return server; return server;
+57
View File
@@ -0,0 +1,57 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* What is actually being served (M16-T01, extracted in M19).
*
* Kept apart from the routes because the health probe, the status page and the
* sidebar all need the same answer, and a second copy would eventually give a
* different one.
*/
const here = path.dirname(fileURLToPath(import.meta.url));
export const VERSION = (() => {
try {
return JSON.parse(readFileSync(path.join(here, '../../../package.json'), 'utf8')).version;
} catch {
return 'inconnue';
}
})();
/**
* Newest file of the served interface.
*
* Read from disk rather than frozen at startup: the front-end is served from
* disk on every request, so a marker captured at boot would keep announcing an
* old build after an upload — the exact confusion it exists to prevent. Cached
* briefly so a health check does not walk the tree each time.
*/
const BUILD_TTL_MS = 10_000;
let cache = { at: null, readAt: 0 };
export function buildAt() {
if (cache.readAt && Date.now() - cache.readAt < BUILD_TTL_MS) return cache.at;
const root = path.join(here, '../public');
let newest = 0;
const walk = (directory) => {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) walk(target);
else newest = Math.max(newest, statSync(target).mtimeMs);
}
};
try {
walk(root);
} catch {
cache = { at: null, readAt: Date.now() };
return null;
}
cache = { at: newest > 0 ? new Date(newest).toISOString() : null, readAt: Date.now() };
return cache.at;
}
+27 -3
View File
@@ -101,7 +101,7 @@ export const SECTIONS = Object.freeze([
'Toujours dans **OAuth2 → Redirects**, ajoute exactement l’URL affichée dans **Paramètres → Tableau de bord** : c’est l’adresse par laquelle tu ouvres le site, suivie de `/auth/callback`.', 'Toujours dans **OAuth2 → Redirects**, ajoute exactement l’URL affichée dans **Paramètres → Tableau de bord** : c’est l’adresse par laquelle tu ouvres le site, suivie de `/auth/callback`.',
'Si le site répond sur un port différent de celui annoncé par ton hébergeur, c’est bien le port que tu utilises dans le navigateur qu’il faut déclarer.', 'Si le site répond sur un port différent de celui annoncé par ton hébergeur, c’est bien le port que tu utilises dans le navigateur qu’il faut déclarer.',
'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.', 'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.',
'Laisse `WEB_HOST` sur `127.0.0.1` et place un reverse proxy HTTPS devant, sauf en développement local.', 'Choisis `WEB_HOST` : `127.0.0.1` derrière un reverse proxy local, `0.0.0.0` dans un conteneur ou sur un panel d’hébergement.',
], ],
links: [{ label: 'OAuth2 du Developer Portal', url: 'https://discord.com/developers/applications' }], links: [{ label: 'OAuth2 du Developer Portal', url: 'https://discord.com/developers/applications' }],
}, },
@@ -230,7 +230,7 @@ export const VARIABLES = Object.freeze([
key: 'CHANNEL_MOD_LOGS_ID', key: 'CHANNEL_MOD_LOGS_ID',
section: 'channels', section: 'channels',
label: 'Salon des logs de modération', label: 'Salon des logs de modération',
help: 'Avertissements, exclusions, bannissements.', help: 'Avertissements, mises en sourdine, bannissements.',
type: 'snowflake', type: 'snowflake',
}, },
{ {
@@ -438,7 +438,7 @@ export const VARIABLES = Object.freeze([
key: 'WEB_HOST', key: 'WEB_HOST',
section: 'web', section: 'web',
label: 'Interface d’écoute', label: 'Interface d’écoute',
help: 'Garde `127.0.0.1` et place un reverse proxy HTTPS devant. `0.0.0.0` expose le site sur le réseau.', help: 'Derrière un reverse proxy installé sur la même machine, garde `127.0.0.1`. Dans un conteneur ou sur un panel d’hébergement (Pterodactyl, Docker…), il faut `0.0.0.0` : sinon le site n’écoute que sur la boucle locale et reste injoignable de l’extérieur.',
type: 'text', type: 'text',
default: '127.0.0.1', default: '127.0.0.1',
restartRequired: true, restartRequired: true,
@@ -499,6 +499,15 @@ export const VARIABLES = Object.freeze([
generator: 'hex16', generator: 'hex16',
advanced: true, advanced: true,
}, },
{
key: 'WEB_PUBLIC_STATUS',
section: 'web',
label: 'Page de statut publique',
help: 'Publie `/status` : bot en ligne, dernier déploiement par environnement, dernières releases. Les dépôts privés n’y apparaissent jamais par leur nom.',
type: 'bool',
default: 'true',
restartRequired: true,
},
{ {
key: 'WEB_ALLOW_COMMAND_DEPLOYS', key: 'WEB_ALLOW_COMMAND_DEPLOYS',
section: 'web', section: 'web',
@@ -711,6 +720,21 @@ export function crossCheck(values) {
if (!read('WEB_SESSION_SECRET')) { if (!read('WEB_SESSION_SECRET')) {
warnings.push('Sans `WEB_SESSION_SECRET`, toutes les sessions sont perdues à chaque redémarrage.'); warnings.push('Sans `WEB_SESSION_SECRET`, toutes les sessions sont perdues à chaque redémarrage.');
} }
const publicHost = (() => {
try {
return new URL(read('WEB_PUBLIC_URL')).hostname;
} catch {
return '';
}
})();
const localOnly = ['127.0.0.1', 'localhost', '::1'];
if (read('WEB_HOST') === '127.0.0.1' && publicHost && !localOnly.includes(publicHost)) {
warnings.push(
`\`WEB_HOST=127.0.0.1\` n'écoute que sur la boucle locale, alors que le site est annoncé sur « ${publicHost} » : il sera injoignable, sauf si un reverse proxy tourne sur la même machine. Dans un conteneur ou sur un panel d'hébergement, mets \`0.0.0.0\`.`,
);
}
if (read('WEB_HOST') === '0.0.0.0' && !read('WEB_PUBLIC_URL').startsWith('https://')) { if (read('WEB_HOST') === '0.0.0.0' && !read('WEB_PUBLIC_URL').startsWith('https://')) {
warnings.push('`WEB_HOST=0.0.0.0` sans HTTPS expose les cookies de session en clair sur le réseau.'); warnings.push('`WEB_HOST=0.0.0.0` sans HTTPS expose les cookies de session en clair sur le réseau.');
} }
+197
View File
@@ -0,0 +1,197 @@
/**
* Public status page, rendered on the server (M19).
*
* Same reasoning as the wiki: a page that needs JavaScript to say whether the
* service is up is a page that reads as blank to a monitor, a crawler, or
* anyone on a connection bad enough to be checking the status in the first
* place. There is no script tag here, and the refresh is a meta tag.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
const REFRESH_SECONDS = 60;
const STATE_LABELS = {
ok: 'Opérationnel',
down: 'Hors ligne',
busy: 'En cours',
unknown: 'Inconnu',
};
const DEPLOY_LABELS = {
success: 'Déployé',
failed: 'Échec',
running: 'En cours',
pending: 'En attente',
};
function duration(ms) {
const seconds = Math.floor(Number(ms) / 1000);
if (!Number.isFinite(seconds) || seconds < 0) return '—';
const days = Math.floor(seconds / 86_400);
const hours = Math.floor((seconds % 86_400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days} j ${hours} h`;
if (hours > 0) return `${hours} h ${minutes} min`;
if (minutes > 0) return `${minutes} min`;
return `${seconds} s`;
}
function moment(value) {
if (!value) return '—';
const date = new Date(String(value).includes('T') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return '—';
return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
}
const pill = (tone, label) => `<span class="status-pill status-pill-${escape(tone)}">${escape(label)}</span>`;
const tile = (label, value, hint) => `
<div class="status-tile">
<span class="status-tile-label">${escape(label)}</span>
<strong class="status-tile-value">${escape(value)}</strong>
${hint ? `<span class="status-tile-hint">${escape(hint)}</span>` : ''}
</div>`;
function environmentRows(environments) {
if (environments.length === 0) {
return '<p class="status-empty">Aucun déploiement enregistré pour l’instant.</p>';
}
return `<table class="status-table">
<thead>
<tr><th>Environnement</th><th>Dépôt</th><th>Version</th><th>État</th><th>Le</th></tr>
</thead>
<tbody>
${environments
.map(
(entry) => `<tr>
<td><strong>${escape(entry.environment)}</strong></td>
<td>${entry.repository ? escape(entry.repository) : '<span class="status-muted">privé</span>'}</td>
<td>${entry.releaseTag ? `<code>${escape(entry.releaseTag)}</code>` : '—'}</td>
<td>${pill(entry.tone, DEPLOY_LABELS[entry.status] ?? entry.status)}</td>
<td class="status-muted">${escape(moment(entry.finishedAt))}</td>
</tr>`,
)
.join('\n ')}
</tbody>
</table>`;
}
function releaseList(releases) {
if (releases.length === 0) {
return '<p class="status-empty">Aucune release publiée pour l’instant.</p>';
}
return `<ul class="status-releases">
${releases
.map((release) => {
const label = `${release.repository} · ${release.name}`;
const title = release.htmlUrl
? `<a href="${escape(release.htmlUrl)}">${escape(label)}</a>`
: escape(label);
return `<li>
<div>${title}${release.prerelease ? ` ${pill('busy', 'préversion')}` : ''}</div>
<span class="status-muted">${escape(moment(release.publishedAt))}</span>
</li>`;
})
.join('\n ')}
</ul>`;
}
function footer(links) {
const entries = [
['/wiki', 'Documentation'],
['/terms-of-service', 'Conditions d’utilisation'],
['/privacy-policy', 'Politique de confidentialité'],
links.website && [links.website, 'Site'],
links.forge && [links.forge, 'Forge'],
links.discordInvite && [links.discordInvite, 'Discord'],
].filter(Boolean);
return `<footer class="status-footer">${entries
.map(([href, label]) => `<a href="${escape(href)}">${escape(label)}</a>`)
.join(' · ')}</footer>`;
}
/** Turns a snapshot from `status-service.js` into the finished page. */
export function renderStatus(snapshot) {
const { bot } = snapshot;
const failing = snapshot.environments.filter((entry) => entry.status === 'failed');
// The banner states the worst true thing: a green headline above a failed
// deployment is how a status page loses the only thing it has.
const headline = !bot.online
? { tone: 'down', title: 'Le bot est hors ligne', detail: 'Le service ne répond pas à Discord.' }
: failing.length > 0
? {
tone: 'busy',
title: 'Service opérationnel, déploiement en échec',
detail: `Le bot répond, mais ${failing.length} environnement(s) n’ont pas reçu leur dernière mise à jour.`,
}
: { tone: 'ok', title: 'Tous les services fonctionnent', detail: 'Le bot répond à Discord.' };
return `<!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="État en direct des services FWS : bot Discord, déploiements et releases." />
<meta name="robots" content="index, follow" />
<meta http-equiv="refresh" content="${REFRESH_SECONDS}" />
<title>État des services · FWS</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/styles.css" />
</head>
<body class="status-body">
<main class="status-page">
<header class="status-head">
<a class="status-brand" href="/wiki">
<img src="/favicon.svg" alt="" width="40" height="40" />
<div><strong>FWS</strong><span>État des services</span></div>
</a>
<span class="status-muted">Actualisé automatiquement toutes les ${REFRESH_SECONDS} secondes</span>
</header>
<section class="status-banner status-banner-${escape(headline.tone)}">
<h1>${escape(headline.title)}</h1>
<p>${escape(headline.detail)}</p>
</section>
<section class="status-section">
<h2>Bot Discord</h2>
<div class="status-tiles">
${tile('État', STATE_LABELS[bot.state] ?? bot.state)}
${tile('En ligne depuis', duration(bot.uptimeMs), `Démarré le ${moment(bot.startedAt)}`)}
${tile('Latence Discord', bot.pingMs === null ? '—' : `${bot.pingMs} ms`)}
${tile('Version', bot.version)}
</div>
</section>
<section class="status-section">
<h2>Déploiements</h2>
${environmentRows(snapshot.environments)}
</section>
<section class="status-section">
<h2>Dernières releases</h2>
${releaseList(snapshot.releases)}
</section>
<p class="status-muted status-generated">
Relevé du <time datetime="${escape(snapshot.generatedAt)}">${escape(moment(snapshot.generatedAt))}</time>.
Version lisible par une machine : <a href="/api/status">/api/status</a>.
</p>
${footer(snapshot.links)}
</main>
</body>
</html>
`;
}
+133
View File
@@ -0,0 +1,133 @@
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { lastDeploymentPerEnvironment } from '../../database/repositories/deploy-repository.js';
import { org, repos, splitRepository } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { VERSION } from './build-info.js';
/**
* What the public status page and `/api/status` both answer with (M19).
*
* Two rules shape this file. The page is **public**, so nothing here may name
* something the organization has not made public — a private repository leaking
* through a deployment row would be a real disclosure. And it is **unauthenticated**,
* so it may not turn a page load into a forge request: everything from Gitea is
* cached, and a failed refresh serves the previous answer rather than none.
*/
const log = createLogger('web:status');
const CACHE_TTL_MS = 60_000;
let cache = { at: 0, publicRepositories: null, releases: [] };
/** `success` is the only state worth claiming; everything else is spelled out. */
const DEPLOY_TONES = {
success: 'ok',
failed: 'down',
running: 'busy',
pending: 'busy',
};
async function refreshForge() {
if (!isGiteaConfigured()) return;
if (Date.now() - cache.at < CACHE_TTL_MS) return;
const repositories = await org.listRepos({ limit: 50 }).catch((error) => {
log.debug('Could not refresh the public repository list', error);
return null;
});
if (!repositories) return;
const open = repositories.filter((repository) => !repository.private && !repository.archived);
// One release request per repository would grow with the organization; the
// three most recently touched are what a status page is read for anyway.
const recent = open
.slice()
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
.slice(0, 3);
const releases = (
await Promise.all(
recent.map(async (repository) => {
const parts = splitRepository(repository.full_name);
if (!parts) return null;
const release = await repos.latestRelease(parts.owner, parts.repo).catch(() => null);
if (!release || release.draft) return null;
return {
repository: repository.full_name,
tag: release.tag_name,
name: release.name || release.tag_name,
prerelease: Boolean(release.prerelease),
publishedAt: release.published_at ?? release.created_at ?? null,
htmlUrl: release.html_url ?? null,
};
}),
)
).filter(Boolean);
cache = {
at: Date.now(),
publicRepositories: new Set(open.map((repository) => repository.full_name)),
releases,
};
}
/**
* Deployment rows, stripped of anything the public has no business seeing.
*
* A repository the forge does not list as public is kept as a row — the
* environment is still meaningful — but loses its name.
*/
function environments() {
const guildId = env.discord.guildId;
if (!guildId) return [];
const rows = lastDeploymentPerEnvironment(guildId);
const known = cache.publicRepositories;
return rows.map((row) => ({
environment: row.environment,
repository: !known || known.has(row.repository) ? row.repository : null,
status: row.status,
tone: DEPLOY_TONES[row.status] ?? 'unknown',
releaseTag: row.release_tag ?? null,
finishedAt: row.finished_at ?? null,
}));
}
/** The snapshot behind `/status` and `/api/status`. Never throws. */
export async function statusSnapshot({ client = null, startedAt = Date.now() } = {}) {
await refreshForge().catch((error) => log.debug('Status refresh failed', error));
const online = Boolean(client?.isReady?.());
return {
bot: {
online,
state: online ? 'ok' : 'down',
uptimeMs: Date.now() - startedAt,
startedAt: new Date(startedAt).toISOString(),
version: VERSION,
// Round-trip to Discord: the one number that says the link is healthy
// rather than merely established.
pingMs: typeof client?.ws?.ping === 'number' && client.ws.ping >= 0 ? client.ws.ping : null,
},
environments: environments(),
releases: cache.releases,
links: {
website: env.links.website || null,
docs: env.links.docs || null,
discordInvite: env.links.discordInvite || null,
archRepo: env.links.archRepo || null,
forge: isGiteaConfigured() ? env.gitea.url : null,
},
generatedAt: new Date().toISOString(),
};
}
/** Lets the tests start from a known state. */
export function resetStatusCache() {
cache = { at: 0, publicRepositories: null, releases: [] };
}
+182
View File
@@ -0,0 +1,182 @@
import { env } from '../../config/env.js';
import { render as renderMarkdown } from '../public/core/markdown.js';
import { pagePath } from './wiki-seed.js';
/**
* Server-rendered wiki (M17).
*
* The public documentation is delivered as finished HTML rather than assembled
* in the browser. A terms page that needs JavaScript to show its text is a page
* that reads as blank to anything that does not run scripts — a platform
* checking the link before approving an application, a crawler, a reader with
* scripts disabled — and those are exactly the readers it exists for.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
const document = ({ title, description, body, noindex = false }) => `<!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="${escape(description)}" />
<meta name="robots" content="${noindex ? 'noindex, nofollow' : 'index, follow'}" />
<title>${escape(title)}</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">
${body}
</body>
</html>
`;
/** Sidebar: the page tree and a search box that works without scripts. */
function sidebar(categories, currentSlug, term = '') {
const groups = categories
.map(
(category) => `
<div class="nav-group">${escape(category.name)}</div>
${category.pages
.map(
(page) =>
`<a href="${escape(page.path ?? pagePath(page.slug))}"${
page.slug === currentSlug ? ' class="active" aria-current="page"' : ''
}>${escape(page.title)}</a>`,
)
.join('\n ')}`,
)
.join('\n');
return ` <aside class="wiki-side">
<a class="wiki-brand" href="/wiki">
<img src="/favicon.svg" alt="" width="36" height="36" />
<div><strong>FWS</strong><span>Documentation</span></div>
</a>
<form class="wiki-search" method="get" action="/wiki">
<input class="input" type="search" name="q" value="${escape(term)}" placeholder="Rechercher…" aria-label="Rechercher dans la documentation" />
</form>
<nav class="wiki-nav">
${groups}
</nav>
</aside>`;
}
/** Table of contents, built from the headings the renderer collected. */
const contents = (headings) =>
headings.length < 2
? ''
: ` <nav class="wiki-toc">
<div class="nav-group">Sur cette page</div>
${headings
.map(
(heading) =>
`<a href="#${escape(heading.id)}" data-level="${heading.level}">${escape(heading.text)}</a>`,
)
.join('\n ')}
</nav>`;
const footerLinks = () => {
const links = [
env.links.website && `<a href="${escape(env.links.website)}">Site</a>`,
env.links.docs && `<a href="${escape(env.links.docs)}">Documentation</a>`,
`<a href="/terms-of-service">Conditions d'utilisation</a>`,
`<a href="/privacy-policy">Politique de confidentialité</a>`,
].filter(Boolean);
return `<footer class="wiki-footer">${links.join(' · ')}</footer>`;
};
const shell = (categories, currentSlug, main, term) => ` <div class="wiki-shell">
${sidebar(categories, currentSlug, term)}
<main class="wiki-main">
${main}
${footerLinks()}
</main>
</div>`;
/** A page, with its body already turned into HTML. */
export function renderPage(page, categories) {
const { html, headings } = renderMarkdown(page.content);
const updated = new Date(`${page.updated_at}Z`);
const main = ` <div class="wiki-article">
<article>
<p class="muted">${escape(page.category)}</p>
<h1>${escape(page.title)}</h1>
${page.summary ? `<p class="wiki-summary">${escape(page.summary)}</p>` : ''}
<div class="wiki-content">
${html}
</div>
<footer class="muted wiki-updated">
Dernière modification :
<time datetime="${escape(updated.toISOString())}">${updated.toLocaleDateString('fr-FR', {
dateStyle: 'long',
})}</time>
</footer>
</article>
${contents(headings)}
</div>`;
return document({
title: `${page.title} · Documentation FWS`,
description: page.summary || `${page.title} — documentation de l'organisation FWS.`,
body: shell(categories, page.slug, main),
});
}
/** Landing page, and the search results when a term is given. */
export function renderIndex(categories, { term = '', results = null } = {}) {
const list = (pages) =>
pages.length === 0
? '<p class="empty">Aucun résultat.</p>'
: `<ul class="wiki-index">${pages
.map(
(page) =>
`<li><a href="${escape(page.path ?? pagePath(page.slug))}">${escape(page.title)}</a>${
page.summary ? ` — <span class="muted">${escape(page.summary)}</span>` : ''
}</li>`,
)
.join('')}</ul>`;
const main = results
? ` <article>
<h1>Recherche</h1>
<p class="muted">${results.length} résultat(s) pour « ${escape(term)} ».</p>
${list(results)}
</article>`
: ` <article>
<h1>Documentation FWS</h1>
<p class="wiki-summary">Tout ce qu'il faut savoir sur le bot et l'organisation.</p>
${categories
.map((category) => `<h2>${escape(category.name)}</h2>${list(category.pages)}`)
.join('\n ')}
</article>`;
return document({
title: 'Documentation FWS',
description: "Documentation publique de l'organisation open source FWS.",
body: shell(categories, null, main, term),
});
}
export function renderNotFound(categories) {
const main = ` <article>
<h1>Page introuvable</h1>
<p class="muted">Cette page n'existe pas, ou n'est pas encore publiée.</p>
<p><a href="/wiki">Revenir à la documentation</a></p>
</article>`;
return document({
title: 'Page introuvable · Documentation FWS',
description: 'Page introuvable.',
body: shell(categories, null, main),
noindex: true,
});
}
+260
View File
@@ -0,0 +1,260 @@
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');
/**
* Pages served at the root rather than under `/wiki/`.
*
* Discord, and most platforms, ask for a terms URL and a privacy URL; pasting
* `/wiki/...` in those fields reads like an afterthought.
*/
export const ROOT_PAGES = Object.freeze(['terms-of-service', 'privacy-policy']);
/** Public address of a page, root pages included. */
export const pagePath = (slug) => (ROOT_PAGES.includes(slug) ? `/${slug}` : `/wiki/${slug}`);
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**](/terms-of-service) — ce à quoi tu t'engages en utilisant le bot.
- [**Politique de confidentialité**](/privacy-policy) — 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: 'terms-of-service',
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: 'privacy-policy',
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;
}
+15
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { after, before, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import { listActions, recordAction } from '../src/database/repositories/moderation-repository.js';
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js'; import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
describe('database', () => { describe('database', () => {
@@ -22,6 +23,20 @@ describe('database', () => {
assert.equal(getSetting('guild-b', 'welcome'), null); assert.equal(getSetting('guild-b', 'welcome'), null);
}); });
it('records a lifted sanction next to the sanction it lifts', () => {
// `/unmute` and `/unban` go through the same CHECK constraint as `/mute`
// and `/ban`, so a migration that forgets them breaks the history.
for (const action of ['unban', 'unmute']) {
recordAction({ guildId: 'g', action, moderatorId: 'mod', targetId: 'u', reason: 'Erreur' });
}
const rows = listActions({ guildId: 'g', targetId: 'u' });
assert.deepEqual(
rows.map((row) => row.action).sort(),
['unban', 'unmute'],
);
});
it('prevents two open tickets for the same author and category', () => { it('prevents two open tickets for the same author and category', () => {
const insert = getDatabase().prepare( const insert = getDatabase().prepare(
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')", "INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
+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/);
});
});
+24
View File
@@ -94,6 +94,30 @@ describe('webhook entry points', () => {
}); });
}); });
describe('moderation labels', () => {
it('tells every action apart by wording and emoji', async () => {
const { MODERATION_ACTIONS } = await import('../src/config/constants.js');
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
const emojis = Object.values(MODERATION_ACTIONS).map((meta) => meta.emoji);
assert.ok(emojis.every(Boolean), 'an action has no emoji');
assert.equal(new Set(emojis).size, emojis.length, 'two actions share an emoji');
const labels = Object.keys(MODERATION_ACTIONS).map(moderationLabel);
assert.equal(new Set(labels).size, labels.length, 'two actions read the same');
assert.equal(moderationLabel('inconnu'), 'inconnu', 'an unknown action must stay readable');
});
it('never reads a mute like a kick', async () => {
// Reported from the moderation log channel: a timeout was filed as a
// temporary kick because both labels sat next to each other.
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
assert.equal(moderationLabel('mute'), '🔇 Mise en sourdine');
assert.equal(moderationLabel('kick'), '👢 Expulsion');
});
});
describe('event modules', () => { describe('event modules', () => {
it('exports a name and a handler', async () => { it('exports a name and a handler', async () => {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
/**
* Importing Gitea issues onto a board (M18).
*
* A stand-in forge answers on a real socket, and the environment is set before
* the modules that read it are loaded — hence the dynamic imports.
*/
let issues = [];
const forge = createServer((request, response) => {
if (!request.url.includes('/issues')) {
response.writeHead(404).end();
return;
}
const state = new URL(request.url, 'http://x').searchParams.get('state');
const body = state === 'all' ? issues : issues.filter((issue) => issue.state === 'open');
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(body));
});
await new Promise((resolve) => forge.listen(0, '127.0.0.1', resolve));
process.env.GITEA_URL = `http://127.0.0.1:${forge.address().port}`;
process.env.GITEA_TOKEN = 'jeton-de-test';
process.env.GITEA_OWNER = 'FWS';
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
const { createBoard, listCards, listColumns } = await import(
'../src/database/repositories/project-repository.js'
);
const { createApiToken } = await import('../src/database/repositories/web-session-repository.js');
const { hashToken } = await import('../src/web/auth/session.js');
const { createHandler } = await import('../src/web/server.js');
const TOKEN = 'fws_import-test';
describe('importing issues from Gitea', () => {
let app;
let board;
let columns;
before(async () => {
initDatabase(':memory:');
createApiToken({ name: 'import', tokenHash: hashToken(TOKEN), prefix: 'fws_impo', accessLevel: 3 });
app = createServer(createHandler({ client: null }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
await new Promise((resolve) => forge.close(resolve));
closeDatabase();
});
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards;');
board = createBoard({ guildId: '', scope: 'org', name: 'Organisation' });
columns = listColumns(board.id);
issues = [
{ number: 1, title: 'Corriger le démarrage', state: 'open', body: 'Détails', labels: [{ name: 'bug' }] },
{ number: 2, title: 'Documenter le wiki', state: 'open', body: null, labels: [] },
{ number: 3, title: 'Ancienne demande', state: 'closed', body: null, labels: [] },
];
});
const call = (path, body) =>
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
method: 'POST',
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const importInto = (body = {}) =>
call(`/api/projects/${board.id}/import`, { repository: 'FWS/FWS-Arch', ...body }).then((response) =>
response.json(),
);
it('creates one card per open issue', async () => {
const result = await importInto();
assert.equal(result.imported, 2);
assert.equal(result.column, 'À faire');
assert.deepEqual(
listCards(board.id)
.map((card) => card.title)
.sort(),
['Corriger le démarrage', 'Documenter le wiki'],
);
});
it('records the issue each card came from', async () => {
await importInto();
const card = listCards(board.id).find((entry) => entry.title === 'Corriger le démarrage');
assert.equal(card.issue_ref, 'FWS/FWS-Arch#1');
assert.deepEqual(card.labels, ['bug']);
assert.match(card.body, /Détails/);
});
/** The button has to survive being pressed twice. */
it('skips what is already on the board', async () => {
await importInto();
const second = await importInto();
assert.equal(second.imported, 0);
assert.equal(second.skipped, 2);
assert.equal(listCards(board.id).length, 2);
});
it('brings the closed issues in when asked', async () => {
const result = await importInto({ state: 'all' });
assert.equal(result.imported, 3);
});
it('imports into the chosen column', async () => {
const review = columns.find((column) => column.name === 'En revue');
const result = await importInto({ columnId: review.id });
assert.equal(result.column, 'En revue');
assert.ok(listCards(board.id).every((card) => card.column_id === review.id));
});
/** Importing straight into « Terminé » is never what anyone means. */
it('never imports into a column of another board', async () => {
const other = createBoard({ guildId: '', scope: 'repo', repository: 'FWS/site', name: 'Site' });
const foreign = listColumns(other.id)[0];
const result = await importInto({ columnId: foreign.id });
assert.equal(result.column, 'À faire');
assert.equal(listCards(other.id).length, 0);
});
it('reports what it found even when nothing is new', async () => {
issues = [];
const result = await importInto();
assert.equal(result.found, 0);
assert.equal(result.imported, 0);
assert.equal(result.repository, 'FWS/FWS-Arch');
});
});
+351
View File
@@ -0,0 +1,351 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
DEFAULT_COLUMNS,
addCard,
addColumn,
countCardsInColumn,
createBoard,
getBoardByRepository,
getCard,
getOrgBoard,
listBoards,
listCards,
listCardsForAssignee,
listColumns,
moveCard,
removeBoard,
removeColumn,
} from '../src/database/repositories/project-repository.js';
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
import { hashToken } from '../src/web/auth/session.js';
import { createHandler } from '../src/web/server.js';
/** Kanban boards (M18). */
const GUILD = '';
const board = (overrides = {}) =>
createBoard({ guildId: GUILD, scope: 'repo', repository: 'FWS/FWS-Arch', name: 'FWS Arch', ...overrides });
const columnsOf = (id) => listColumns(id);
describe('project boards', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM project_boards;'));
it('creates a board with the FWS columns', () => {
const created = board();
assert.deepEqual(
columnsOf(created.id).map((column) => column.name),
DEFAULT_COLUMNS.map((column) => column.name),
);
});
it('marks the last column as the finished one', () => {
const columns = columnsOf(board().id);
assert.equal(columns.at(-1).is_done, true);
assert.equal(columns[0].is_done, false);
});
it('carries the default limit on « En cours »', () => {
const inProgress = columnsOf(board().id).find((column) => column.name === 'En cours');
assert.equal(inProgress.wip_limit, 3);
});
it('allows one board per repository', () => {
board();
assert.throws(() => board(), /UNIQUE/);
});
it('allows a single organization board', () => {
createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
assert.throws(() => createBoard({ guildId: GUILD, scope: 'org', name: 'Autre' }), /UNIQUE/);
});
it('finds a board by its repository and by its scope', () => {
const repo = board();
const org = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
assert.equal(getBoardByRepository(GUILD, 'FWS/FWS-Arch').id, repo.id);
assert.equal(getOrgBoard(GUILD).id, org.id);
assert.equal(listBoards(GUILD).length, 2);
});
it('takes its columns and cards with it when deleted', () => {
const created = board();
addCard({ boardId: created.id, columnId: columnsOf(created.id)[0].id, title: 'Une tâche' });
removeBoard(created.id);
assert.equal(listColumns(created.id).length, 0);
assert.equal(listCards(created.id).length, 0);
});
});
describe('cards', () => {
let created;
let columns;
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards;');
created = board();
columns = columnsOf(created.id);
});
const add = (title, columnId = columns[0].id) => addCard({ boardId: created.id, columnId, title });
const titles = (columnId) =>
listCards(created.id)
.filter((card) => card.column_id === columnId)
.sort((a, b) => a.position - b.position)
.map((card) => card.title);
it('appends a card at the end of its column', () => {
add('un');
add('deux');
assert.deepEqual(titles(columns[0].id), ['un', 'deux']);
});
it('keeps labels as a list', () => {
const card = addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'Étiquetée',
labels: ['bug', 'urgent'],
});
assert.deepEqual(getCard(card.id).labels, ['bug', 'urgent']);
});
it('moves a card to another column', () => {
const card = add('un');
add('deux');
moveCard(card.id, { columnId: columns[1].id, position: 0 });
assert.deepEqual(titles(columns[0].id), ['deux']);
assert.deepEqual(titles(columns[1].id), ['un']);
});
it('inserts at the requested rank', () => {
add('un');
add('deux');
const third = add('trois');
moveCard(third.id, { columnId: columns[0].id, position: 1 });
assert.deepEqual(titles(columns[0].id), ['un', 'trois', 'deux']);
});
/** Positions must stay contiguous, or the next drop lands somewhere odd. */
it('renumbers both columns after a move', () => {
add('un');
const second = add('deux');
add('trois');
moveCard(second.id, { columnId: columns[1].id, position: 0 });
const left = listCards(created.id).filter((card) => card.column_id === columns[0].id);
assert.deepEqual(left.map((card) => card.position).sort(), [0, 1], 'la colonne quittée garde un trou');
assert.equal(getCard(second.id).position, 0);
});
it('survives a move onto itself', () => {
const card = add('un');
add('deux');
moveCard(card.id, { columnId: columns[0].id, position: 1 });
assert.deepEqual(titles(columns[0].id), ['deux', 'un']);
});
it('counts the cards of a column', () => {
add('un');
add('deux');
assert.equal(countCardsInColumn(columns[0].id), 2);
assert.equal(countCardsInColumn(columns[1].id), 0);
});
it('lists what one member carries, soonest deadline first', () => {
addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'plus tard',
assigneeId: 'u1',
dueAt: '2026-12-01',
});
addCard({
boardId: created.id,
columnId: columns[0].id,
title: 'bientôt',
assigneeId: 'u1',
dueAt: '2026-10-01',
});
addCard({ boardId: created.id, columnId: columns[0].id, title: 'sans date', assigneeId: 'u1' });
addCard({ boardId: created.id, columnId: columns[0].id, title: 'quelqu’un d’autre', assigneeId: 'u2' });
assert.deepEqual(
listCardsForAssignee(GUILD, 'u1').map((card) => card.title),
['bientôt', 'plus tard', 'sans date'],
);
});
it('drops the cards of a removed column', () => {
add('un');
const extra = addColumn({ boardId: created.id, name: 'Bloqué' });
const card = add('deux', extra.id);
removeColumn(extra.id);
assert.equal(getCard(card.id), null);
assert.deepEqual(titles(columns[0].id), ['un']);
});
});
describe('projects over HTTP', () => {
const TOKEN = 'fws_projects-test';
let app;
before(async () => {
initDatabase(':memory:');
createApiToken({
name: 'projects',
tokenHash: hashToken(TOKEN),
prefix: TOKEN.slice(0, 12),
accessLevel: ACCESS_LEVELS.OWNER,
});
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();
});
beforeEach(() => getDatabase().exec('DELETE FROM project_boards;'));
const call = (method, path, body) =>
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
method,
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
it('refuses a board without a session', async () => {
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/projects`);
assert.equal(response.status, 401);
});
it('creates the organization board once', async () => {
assert.equal((await call('POST', '/api/projects', { scope: 'org', name: 'Organisation' })).status, 200);
const again = await call('POST', '/api/projects', { scope: 'org', name: 'Encore' });
assert.equal(again.status, 400);
assert.match((await again.json()).error, /déjà son tableau/);
});
it('refuses a repository that is not owner/name', async () => {
const response = await call('POST', '/api/projects', { scope: 'repo', repository: 'pas-un-depot' });
assert.equal(response.status, 400);
});
it('returns a board with its columns and cards', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const columns = columnsOf(created.id);
await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columns[0].id,
title: 'Première carte',
});
const full = await (await call('GET', `/api/projects/${created.id}`)).json();
assert.equal(full.columns.length, DEFAULT_COLUMNS.length);
assert.equal(full.columns[0].cards[0].title, 'Première carte');
});
it('refuses an issue reference that is not owner/repo#n', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const response = await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columnsOf(created.id)[0].id,
title: 'Liée',
issueRef: 'pas-une-reference',
});
assert.equal(response.status, 400);
assert.match((await response.json()).error, /organisation\/depot#12/);
});
it('reports an overloaded column without refusing the move', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const columns = columnsOf(created.id);
const inProgress = columns.find((column) => column.name === 'En cours');
// Fill it to its limit of three, then push a fourth in. Each step is
// asserted, so a failure cannot cascade into a misleading one later.
const cards = [];
for (const title of ['une', 'deux', 'trois', 'quatre']) {
const response = await call('POST', `/api/projects/${created.id}/cards`, {
columnId: columns[0].id,
title,
});
assert.equal(response.status, 200, `la carte « ${title} » n'a pas été créée`);
cards.push(await response.json());
}
for (const card of cards.slice(0, 3)) {
const response = await call('POST', `/api/projects/${created.id}/cards/${card.id}/move`, {
columnId: inProgress.id,
});
assert.equal(response.status, 200, `le déplacement de « ${card.title} » a échoué`);
assert.equal(
(await response.json()).overloaded,
false,
'la limite ne doit pas être atteinte avant la 4e',
);
}
const response = await call('POST', `/api/projects/${created.id}/cards/${cards[3].id}/move`, {
columnId: inProgress.id,
});
const body = await response.json();
assert.equal(response.status, 200, 'le déplacement doit aboutir malgré la limite');
assert.equal(body.overloaded, true);
assert.equal(countCardsInColumn(inProgress.id), 4);
});
it('keeps a board from losing its last column', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
for (const column of columnsOf(created.id).slice(0, 3)) {
await call('DELETE', `/api/projects/${created.id}/columns/${column.id}`);
}
const last = columnsOf(created.id);
assert.equal(last.length, 1);
const response = await call('DELETE', `/api/projects/${created.id}/columns/${last[0].id}`);
assert.equal(response.status, 400);
});
it('refuses to import when Gitea is not configured', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const response = await call('POST', `/api/projects/${created.id}/import`, {
repository: 'FWS/FWS-Arch',
});
// `GITEA_TOKEN` is unset in the tests, so the import cannot run.
assert.equal(response.status, 400);
assert.match((await response.json()).error, /Gitea/);
});
it('refuses a repository that is not owner/name', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
const response = await call('POST', `/api/projects/${created.id}/import`, { repository: 'nope' });
assert.equal(response.status, 400);
});
it('asks for the name before deleting a board', async () => {
const created = await (await call('POST', '/api/projects', { scope: 'org', name: 'Org' })).json();
assert.equal((await call('DELETE', `/api/projects/${created.id}`, { confirm: 'faux' })).status, 400);
assert.equal((await call('DELETE', `/api/projects/${created.id}`, { confirm: 'Org' })).status, 200);
});
});
+28 -1
View File
@@ -11,6 +11,11 @@ import {
removeNotificationChannel, removeNotificationChannel,
setNotificationChannel, setNotificationChannel,
} from '../src/database/repositories/notification-repository.js'; } from '../src/database/repositories/notification-repository.js';
import {
clearRulesMessage,
getRulesMessage,
setRulesMessage,
} from '../src/database/repositories/rules-repository.js';
import { import {
castVote, castVote,
closePoll, closePoll,
@@ -29,7 +34,7 @@ import {
const reset = () => const reset = () =>
getDatabase().exec( getDatabase().exec(
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;', 'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels; DELETE FROM rules_messages;',
); );
describe('ticket repository', () => { describe('ticket repository', () => {
@@ -187,3 +192,25 @@ describe('notification repository', () => {
assert.equal(removeNotificationChannel('g', 'release'), 0); assert.equal(removeNotificationChannel('g', 'release'), 0);
}); });
}); });
describe('rules repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('keeps one rules message per guild and replaces it', () => {
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1', updatedBy: 'mod' });
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm2', updatedBy: 'mod' });
const stored = getRulesMessage('g');
assert.equal(stored.message_id, 'm2');
assert.equal(stored.updated_by, 'mod');
assert.equal(getRulesMessage('other'), null);
});
it('forgets the message when it is cleared', () => {
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1' });
assert.equal(clearRulesMessage('g'), 1);
assert.equal(getRulesMessage('g'), null);
});
});
+140
View File
@@ -0,0 +1,140 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import { publishRules, rulesStatus } from '../src/services/rules/rules-service.js';
// The dashboard relies on `CHANNEL_RULES_ID`, which no CI run declares, so the
// channel is passed explicitly here rather than read from the environment.
const RULES_CHANNEL = '1234567890123456789';
/** A Discord client reduced to what saving the rules touches. */
function harness({ pinFails = false, notEditable = false } = {}) {
const state = { sent: [], edited: [], pinned: [], messages: new Map() };
// Discord edits a message in place: the id, the link and the pin stay.
const withEdit = (message) => ({
...message,
edit: async ({ embeds }) => {
state.edited.push({ id: message.id, description: embeds[0].toJSON().description });
return message;
},
});
const channel = {
isSendable: () => true,
async send(payload) {
const id = `message-${state.sent.length + 1}`;
state.sent.push({ id, payload });
state.messages.set(id, { id, editable: !notEditable });
return {
...withEdit({ id, url: `https://discord.test/${id}` }),
pin: async () => {
if (pinFails) throw new Error('Missing Permissions');
state.pinned.push(id);
},
};
},
messages: {
fetch: async (id) => {
const message = state.messages.get(id);
return message ? withEdit(message) : null;
},
},
};
return { state, client: { channels: { fetch: async () => channel } } };
}
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
publishRules(client, { guildId: 'g', markdown, actorId: 'mod', channelId: RULES_CHANNEL });
const description = (entry) => entry.payload.embeds[0].toJSON().description;
describe('rules service', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
it('sends and pins the rules the first time', async () => {
const { state, client } = harness();
const result = await publish(client, '**Pas de contenu illégal.**');
assert.equal(state.sent.length, 1);
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
assert.deepEqual(state.pinned, ['message-1']);
assert.deepEqual({ pinned: result.pinned, edited: result.edited }, { pinned: true, edited: false });
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
});
it('edits the published message instead of sending a second one', async () => {
const { state, client } = harness();
await publish(client, 'Version 1');
const result = await publish(client, 'Version 2');
assert.equal(state.sent.length, 1, 'a second message was sent');
assert.deepEqual(state.edited, [{ id: 'message-1', description: 'Version 2' }]);
assert.equal(result.messageId, 'message-1', 'the message id must not change');
assert.equal(result.edited, true);
});
it('sends a new one when the previous message is gone', async () => {
const { state, client } = harness();
await publish(client, 'Version 1');
state.messages.clear();
const result = await publish(client, 'Version 2');
assert.equal(state.sent.length, 2);
assert.equal(result.edited, false);
assert.equal(result.messageId, 'message-2');
});
it('sends a new one when the bot may no longer edit it', async () => {
const { state, client } = harness({ notEditable: true });
await publish(client, 'Version 1');
const result = await publish(client, 'Version 2');
assert.equal(state.sent.length, 2);
assert.equal(result.edited, false);
});
it('publishes even when the bot cannot pin', async () => {
const { state, client } = harness({ pinFails: true });
const result = await publish(client);
assert.deepEqual(state.pinned, []);
assert.equal(result.pinned, false);
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
});
it('refuses an empty or oversized regulation', async () => {
const { client } = harness();
await assert.rejects(() => publish(client, ' '), /vide/);
await assert.rejects(() => publish(client, 'a'.repeat(4001)), /4000 caractères/);
});
it('refuses to publish without a rules channel', async () => {
const { client } = harness();
await assert.rejects(
() => publishRules(client, { guildId: 'g', markdown: 'Règlement', channelId: '' }),
/CHANNEL_RULES_ID/,
);
});
it('reports the configured channel to the dashboard', () => {
assert.deepEqual(rulesStatus('g', RULES_CHANNEL), {
channelId: RULES_CHANNEL,
configured: true,
messageId: null,
publishedAt: null,
publishedBy: null,
});
});
});
+227
View File
@@ -0,0 +1,227 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addCard,
createBoard,
listAssignees,
listCardsForAssignee,
listColumns,
} from '../src/database/repositories/project-repository.js';
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
import { hashToken } from '../src/web/auth/session.js';
import { createHandler } from '../src/web/server.js';
/** « Mes tâches » — cards gathered across every board (M19). */
const GUILD = '';
const ME = '111';
const OTHER = '222';
/** Whole days from today, in the `YYYY-MM-DD` shape the cards store. */
const dayOffset = (days) => {
const date = new Date();
date.setDate(date.getDate() + days);
return date.toISOString().slice(0, 10);
};
let board;
let columns;
function seed() {
getDatabase().exec('DELETE FROM project_boards;');
board = createBoard({ guildId: GUILD, scope: 'repo', repository: 'FWS/FWS-Arch', name: 'FWS Arch' });
columns = listColumns(board.id);
}
const put = (title, overrides = {}) =>
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
describe('cards gathered by assignee', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(seed);
it('carries the column each card sits in', () => {
put('Une tâche', { assigneeId: ME });
const [task] = listCardsForAssignee(GUILD, ME);
assert.equal(task.column_name, 'À faire');
assert.equal(task.column_is_done, false);
assert.equal(task.board_name, 'FWS Arch');
assert.equal(task.repository, 'FWS/FWS-Arch');
});
/** Finishing a card from the list is one move, so the target travels with it. */
it('names the column that would finish the card', () => {
put('Une tâche', { assigneeId: ME });
const done = columns.at(-1);
assert.equal(listCardsForAssignee(GUILD, ME)[0].done_column_id, done.id);
});
it('marks a card already in the finished column', () => {
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'Livrée', assigneeId: ME });
assert.equal(listCardsForAssignee(GUILD, ME)[0].column_is_done, true);
});
it('orders by deadline, undated last', () => {
put('plus tard', { assigneeId: ME, dueAt: dayOffset(9) });
put('sans date', { assigneeId: ME });
put('demain', { assigneeId: ME, dueAt: dayOffset(1) });
assert.deepEqual(
listCardsForAssignee(GUILD, ME).map((task) => task.title),
['demain', 'plus tard', 'sans date'],
);
});
it('ignores what belongs to someone else', () => {
put('à moi', { assigneeId: ME });
put('à l’autre', { assigneeId: OTHER });
assert.deepEqual(
listCardsForAssignee(GUILD, ME).map((task) => task.title),
['à moi'],
);
});
it('lists who carries cards, finished ones excluded from the open count', () => {
put('ouverte', { assigneeId: ME });
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'close', assigneeId: ME });
put('autre', { assigneeId: OTHER });
const [mine] = listAssignees(GUILD).filter((entry) => entry.assigneeId === ME);
assert.equal(mine.total, 2);
assert.equal(mine.open, 1);
});
it('leaves unassigned cards out of the roster', () => {
put('orpheline');
assert.deepEqual(listAssignees(GUILD), []);
});
});
describe('my tasks over HTTP', () => {
const TOKEN = 'fws_tasks-test';
const ANONYMOUS = 'fws_tasks-anon';
let app;
before(async () => {
initDatabase(':memory:');
createApiToken({
name: 'tasks',
tokenHash: hashToken(TOKEN),
prefix: TOKEN.slice(0, 12),
accessLevel: ACCESS_LEVELS.STAFF,
createdBy: ME,
});
// A token with nobody behind it: there is no « me » to answer for.
createApiToken({
name: 'anonyme',
tokenHash: hashToken(ANONYMOUS),
prefix: ANONYMOUS.slice(0, 12),
accessLevel: ACCESS_LEVELS.STAFF,
});
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();
});
beforeEach(seed);
const call = (path, token = TOKEN) =>
fetch(`http://127.0.0.1:${app.address().port}${path}`, {
headers: { Authorization: `Bearer ${token}` },
});
const tasks = (query = '') => call(`/api/me/tasks${query}`).then((response) => response.json());
it('refuses a visitor without a session', async () => {
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/me/tasks`);
assert.equal(response.status, 401);
});
it('answers with the caller’s own cards', async () => {
put('à moi', { assigneeId: ME });
put('à l’autre', { assigneeId: OTHER });
const body = await tasks();
assert.equal(body.self, true);
assert.equal(body.assigneeId, ME);
assert.deepEqual(
body.cards.map((task) => task.title),
['à moi'],
);
});
it('counts what is late, due today and finished', async () => {
put('en retard', { assigneeId: ME, dueAt: dayOffset(-2) });
put('aujourd’hui', { assigneeId: ME, dueAt: dayOffset(0) });
put('plus tard', { assigneeId: ME, dueAt: dayOffset(30) });
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'faite', assigneeId: ME });
const { counts } = await tasks();
assert.deepEqual(counts, { total: 4, open: 3, done: 1, overdue: 1, dueToday: 1 });
});
/** A finished card must not be counted as late, however old its deadline. */
it('never calls a finished card late', async () => {
addCard({
boardId: board.id,
columnId: columns.at(-1).id,
title: 'livrée en retard',
assigneeId: ME,
dueAt: dayOffset(-40),
});
const { counts } = await tasks();
assert.equal(counts.overdue, 0);
assert.equal(counts.done, 1);
});
it('tells the page where each card lives and how to finish it', async () => {
put('une carte', { assigneeId: ME });
const [task] = (await tasks()).cards;
assert.equal(task.boardId, board.id);
assert.equal(task.boardName, 'FWS Arch');
assert.equal(task.columnName, 'À faire');
assert.equal(task.isDone, false);
assert.equal(task.doneColumnId, columns.at(-1).id);
});
it('looks at another member when asked', async () => {
put('à l’autre', { assigneeId: OTHER });
const body = await tasks(`?assignee=${OTHER}`);
assert.equal(body.self, false);
assert.equal(body.assigneeId, OTHER);
assert.equal(body.cards.length, 1);
});
it('offers the members who carry cards', async () => {
put('à moi', { assigneeId: ME });
put('à l’autre', { assigneeId: OTHER });
const ids = (await tasks()).assignees.map((entry) => entry.assigneeId).sort();
assert.deepEqual(ids, [ME, OTHER]);
});
it('explains itself when the caller has no identity', async () => {
const response = await call('/api/me/tasks', ANONYMOUS);
assert.equal(response.status, 400);
assert.match((await response.json()).error, /membre/i);
});
it('skips the forge when only the counters are wanted', async () => {
put('liée', { assigneeId: ME, issueRef: 'FWS/FWS-Arch#1' });
assert.deepEqual((await tasks('?issues=0')).issues, {});
});
});
+24
View File
@@ -88,6 +88,30 @@ describe('env schema', () => {
assert.ok(warnings.some((warning) => warning.includes('rejetés'))); assert.ok(warnings.some((warning) => warning.includes('rejetés')));
}); });
it('warns when a public address is announced but only loopback is bound', () => {
// The failure it prevents: the site answers on the loopback while a domain
// points at it, so every request times out and nothing says why.
const warnings = crossCheck({
WEB_ENABLED: 'true',
WEB_HOST: '127.0.0.1',
WEB_PUBLIC_URL: 'https://bot.example.org',
DISCORD_CLIENT_SECRET: 'x',
WEB_SESSION_SECRET: 'y',
});
assert.ok(warnings.some((warning) => warning.includes('boucle locale')));
});
it('stays quiet when the loopback matches the announced address', () => {
const warnings = crossCheck({
WEB_ENABLED: 'true',
WEB_HOST: '127.0.0.1',
WEB_PUBLIC_URL: 'http://localhost:3080',
DISCORD_CLIENT_SECRET: 'x',
WEB_SESSION_SECRET: 'y',
});
assert.ok(!warnings.some((warning) => warning.includes('boucle locale')));
});
it('warns when the dashboard is exposed without HTTPS', () => { it('warns when the dashboard is exposed without HTTPS', () => {
const warnings = crossCheck({ const warnings = crossCheck({
WEB_ENABLED: 'true', WEB_ENABLED: 'true',
+112
View File
@@ -0,0 +1,112 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { activePath, highlight } from '../src/web/public/core/nav.js';
/**
* Sidebar highlighting (M16-T11).
*
* Tested against a tiny stand-in for the DOM, because getting it wrong leaves
* the sidebar pointing at a page you are not on — a bug that looks like
* nothing and has been reported more than once.
*/
/** Just enough element to satisfy `highlight`: classes, dataset, attributes. */
function link(route) {
const classes = new Set();
const attributes = {};
return {
dataset: { route },
attributes,
classList: {
toggle: (name, on) => (on ? classes.add(name) : classes.delete(name)),
contains: (name) => classes.has(name),
},
setAttribute: (name, value) => (attributes[name] = value),
removeAttribute: (name) => delete attributes[name],
get active() {
return classes.has('active');
},
};
}
const sidebar = (...routes) => {
const links = routes.map(link);
return { links, querySelectorAll: () => links };
};
const activeNames = (bar) => bar.links.filter((entry) => entry.active).map((entry) => entry.dataset.route);
describe('active route', () => {
it('reads the first segment of a hash route', () => {
assert.equal(activePath('#/repos'), 'repos');
assert.equal(activePath('#/settings'), 'settings');
});
it('treats a detail page as its section', () => {
assert.equal(activePath('#/repos/FWS/FWS-Arch'), 'repos');
});
it('ignores a query string', () => {
assert.equal(activePath('#/releases?repo=FWS/Arch'), 'releases');
});
it('maps every spelling of the home page to the same entry', () => {
for (const hash of ['', '#', '#/', '#//']) {
assert.equal(activePath(hash), '', `« ${hash} » should be the home page`);
}
});
});
describe('sidebar highlighting', () => {
it('marks the current entry and only it', () => {
const bar = sidebar('', 'repos', 'settings');
highlight(bar, '#/repos');
assert.deepEqual(activeNames(bar), ['repos']);
});
it('marks the home entry on the home page', () => {
const bar = sidebar('', 'repos');
highlight(bar, '#/');
assert.deepEqual(activeNames(bar), ['']);
});
/** The regression that started all this: home stayed lit on every page. */
it('clears the home entry once elsewhere', () => {
const bar = sidebar('', 'repos');
highlight(bar, '#/');
highlight(bar, '#/repos');
assert.deepEqual(activeNames(bar), ['repos']);
});
it('keeps the section lit on a detail page', () => {
const bar = sidebar('', 'repos', 'releases');
highlight(bar, '#/repos/FWS/FWS-Arch');
assert.deepEqual(activeNames(bar), ['repos']);
});
it('keeps the section lit despite a query string', () => {
const bar = sidebar('', 'releases', 'deploy');
highlight(bar, '#/releases?repo=FWS/Arch');
assert.deepEqual(activeNames(bar), ['releases']);
});
it('lights nothing on an unknown route', () => {
const bar = sidebar('', 'repos');
highlight(bar, '#/inexistant');
assert.deepEqual(activeNames(bar), []);
});
it('announces the current entry to screen readers', () => {
const bar = sidebar('', 'repos');
highlight(bar, '#/repos');
const [home, repos] = bar.links;
assert.equal(repos.attributes['aria-current'], 'page');
assert.equal(home.attributes['aria-current'], undefined);
});
it('survives a link that carries no route', () => {
const bar = { links: [], querySelectorAll: () => [{ ...link(undefined) }] };
assert.doesNotThrow(() => highlight(bar, '#/repos'));
});
});
+100
View File
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { grouped, localPages } from '../src/web/public/core/palette.js';
/**
* Command palette, the parts that hold no DOM (M19).
*
* Both are small and both are the kind of thing that degrades quietly: a
* heading above every line, or a page offered to someone who cannot open it.
*/
const result = (kind, title) => ({ kind, title });
describe('grouping the results', () => {
/** The forge returns issues and pull requests interleaved. */
it('gathers each kind, however they arrive', () => {
const order = grouped([
result('issue', 'i1'),
result('pull', 'p1'),
result('issue', 'i2'),
result('pull', 'p2'),
]).map((entry) => entry.kind);
assert.deepEqual(order, ['issue', 'issue', 'pull', 'pull']);
});
it('keeps the order the server chose inside a group', () => {
const titles = grouped([
result('card', 'première'),
result('page', 'une page'),
result('card', 'seconde'),
])
.filter((entry) => entry.kind === 'card')
.map((entry) => entry.title);
assert.deepEqual(titles, ['première', 'seconde']);
});
it('puts the pages first and the members last', () => {
const order = grouped([
result('member', 'quelqu’un'),
result('repository', 'FWS/x'),
result('page', 'Dépôts'),
]).map((entry) => entry.kind);
assert.deepEqual(order, ['page', 'repository', 'member']);
});
it('sends an unknown kind to the end rather than dropping it', () => {
const order = grouped([result('inconnu', '?'), result('page', 'Dépôts')]).map((entry) => entry.kind);
assert.deepEqual(order, ['page', 'inconnu']);
});
it('survives an empty answer', () => {
assert.deepEqual(grouped([]), []);
});
});
describe('matching the pages locally', () => {
const pages = [
{ path: '', label: 'Vue d’ensemble', group: 'Pilotage' },
{ path: 'tasks', label: 'Mes tâches', group: 'Pilotage' },
{ path: 'repos', label: 'Dépôts', group: 'Code' },
{ path: 'settings', label: 'Paramètres', group: 'Système' },
];
it('lists everything when nothing is typed', () => {
assert.equal(localPages(pages, '').length, pages.length);
});
it('matches on the label', () => {
assert.deepEqual(
localPages(pages, 'tâche').map((entry) => entry.title),
['Mes tâches'],
);
});
/** Typing the section is how people who know the panel navigate it. */
it('matches on the group', () => {
assert.deepEqual(
localPages(pages, 'pilotage').map((entry) => entry.title),
['Vue d’ensemble', 'Mes tâches'],
);
});
it('points at the hash route of each page', () => {
const [overview] = localPages(pages, 'ensemble');
assert.equal(overview.href, '#/');
assert.equal(localPages(pages, 'dépôt')[0].href, '#/repos');
});
/**
* The caller passes only the pages the visitor can see, so a page missing
* from that list must never surface — the palette does no filtering of its own.
*/
it('offers nothing beyond the list it was given', () => {
const visible = pages.filter((page) => page.path !== 'settings');
assert.deepEqual(localPages(visible, 'paramètres'), []);
});
});
+199
View File
@@ -0,0 +1,199 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addCard,
createBoard,
listColumns,
searchCards,
} from '../src/database/repositories/project-repository.js';
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
import { createPage } from '../src/database/repositories/wiki-repository.js';
import { hashToken } from '../src/web/auth/session.js';
import { createHandler } from '../src/web/server.js';
/**
* Global search behind the command palette (M19).
*
* Gitea is deliberately left unconfigured here: the point is that the local
* sources answer on their own, so a forge that is down costs the palette its
* repositories and nothing else.
*/
const GUILD = '';
const TOKEN = 'fws_search-test';
describe('global search', () => {
let app;
let board;
let columns;
before(async () => {
initDatabase(':memory:');
createApiToken({
name: 'recherche',
tokenHash: hashToken(TOKEN),
prefix: TOKEN.slice(0, 12),
accessLevel: ACCESS_LEVELS.STAFF,
});
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();
});
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards; DELETE FROM wiki_pages;');
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
columns = listColumns(board.id);
});
const search = (term) =>
fetch(`http://127.0.0.1:${app.address().port}/api/search?q=${encodeURIComponent(term)}`, {
headers: { Authorization: `Bearer ${TOKEN}` },
});
const results = (term) => search(term).then((response) => response.json());
const card = (title, overrides = {}) =>
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
const page = (title, overrides = {}) =>
createPage({
slug: title.toLowerCase().replaceAll(' ', '-'),
title,
published: true,
category: 'Guides',
...overrides,
});
it('refuses a visitor without a session', async () => {
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/search?q=test`);
assert.equal(response.status, 401);
});
/** One or two letters match half the organization, which helps nobody. */
it('stays silent on a term too short to mean anything', async () => {
card('Pterodactyl');
assert.deepEqual((await results('p')).results, []);
});
it('finds a card and says which board it is on', async () => {
card('Corriger le démarrage');
const [found] = (await results('démarrage')).results;
assert.equal(found.kind, 'card');
assert.equal(found.title, 'Corriger le démarrage');
assert.equal(found.subtitle, 'Organisation · À faire');
assert.equal(found.href, `#/projects/${board.id}`);
});
it('finds a published wiki page at its public address', async () => {
page('Installer FWS Arch', { summary: 'Le guide pas à pas.' });
const [found] = (await results('Installer')).results;
assert.equal(found.kind, 'wiki');
assert.equal(found.href, '/wiki/installer-fws-arch');
assert.equal(found.external, true);
});
it('leaves an unpublished page out of the results', async () => {
page('Brouillon interne', { published: false });
assert.deepEqual((await results('Brouillon')).results, []);
});
/** The legal pages live at the root, not under /wiki. */
it('sends a root page to its own address', async () => {
page('Conditions', { slug: 'terms-of-service' });
const [found] = (await results('Conditions')).results;
assert.equal(found.href, '/terms-of-service');
});
it('gathers several kinds under one answer', async () => {
card('Sauvegarde automatique');
page('Sauvegarde et restauration');
const kinds = (await results('Sauvegarde')).results.map((entry) => entry.kind);
assert.deepEqual(kinds.slice().sort(), ['card', 'wiki']);
});
it('puts the local results first', async () => {
card('Wiki à relire');
page('Wiki public');
assert.equal((await results('Wiki')).results[0].kind, 'card');
});
it('answers with nothing rather than failing when nothing matches', async () => {
const body = await results('introuvable-xyz');
assert.deepEqual(body.results, []);
assert.equal(body.term, 'introuvable-xyz');
});
/** Gitea is not configured here; the palette must still answer. */
it('answers although the forge is absent', async () => {
card('Déploiement');
const response = await search('Déploiement');
assert.equal(response.status, 200);
assert.equal((await response.json()).results.length, 1);
});
});
/** The query behind the palette's card results, exercised without HTTP. */
describe('searching the cards directly', () => {
let board;
let columns;
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards;');
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
columns = listColumns(board.id);
});
const put = (title, overrides = {}) =>
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
it('matches the title', () => {
put('Corriger le démarrage');
put('Documenter le wiki');
assert.deepEqual(
searchCards(GUILD, 'démarrage').map((entry) => entry.title),
['Corriger le démarrage'],
);
});
it('matches the body, the labels and the issue', () => {
put('Sans rapport', { body: 'contient pterodactyl' });
put('Étiquetée', { labels: ['urgent'] });
put('Liée', { issueRef: 'FWS/FWS-Arch#42' });
assert.equal(searchCards(GUILD, 'pterodactyl').length, 1);
assert.equal(searchCards(GUILD, 'urgent').length, 1);
assert.equal(searchCards(GUILD, '#42').length, 1);
});
/** A finished card is still a result, just never the first one. */
it('puts the finished cards last', () => {
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'sujet fini' });
put('sujet en cours');
assert.deepEqual(
searchCards(GUILD, 'sujet').map((entry) => entry.title),
['sujet en cours', 'sujet fini'],
);
});
it('honours the limit', () => {
for (let index = 0; index < 5; index += 1) put(`sujet ${index}`);
assert.equal(searchCards(GUILD, 'sujet', 2).length, 2);
});
});
+28
View File
@@ -95,6 +95,34 @@ describe('dashboard server', () => {
assert.match(response.headers.get('content-type'), /javascript/); assert.match(response.headers.get('content-type'), /javascript/);
}); });
it('never lets a module be cached, so versions cannot drift apart', async () => {
for (const path of ['/app.js', '/core/ui.js', '/views/settings.js', '/styles.css']) {
const response = await app.fetch(path);
assert.equal(response.headers.get('cache-control'), 'no-store', `${path} peut être mis en cache`);
}
});
it('gives its assets a validator so a cache can revalidate', async () => {
const response = await app.fetch('/core/dom.js');
assert.ok(response.headers.get('etag'), 'no ETag on a static asset');
assert.ok(response.headers.get('last-modified'), 'no Last-Modified on a static asset');
});
it('answers 304 when the cached copy is still current', async () => {
const first = await app.fetch('/core/dom.js');
const etag = first.headers.get('etag');
const second = await app.fetch('/core/dom.js', { headers: { 'If-None-Match': etag } });
assert.equal(second.status, 304);
assert.equal(await second.text(), '');
});
it('sends the file again when the validator does not match', async () => {
const response = await app.fetch('/core/dom.js', { headers: { 'If-None-Match': '"stale"' } });
assert.equal(response.status, 200);
assert.ok((await response.text()).length > 0);
});
it('sends the security headers on every response', async () => { it('sends the security headers on every response', async () => {
const response = await app.fetch('/'); const response = await app.fetch('/');
assert.equal(response.headers.get('x-frame-options'), 'DENY'); assert.equal(response.headers.get('x-frame-options'), 'DENY');
+46
View File
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, describe, it } from 'node:test';
/**
* `WEB_PUBLIC_STATUS=false` (M19).
*
* The switch decides what an anonymous visitor may learn about the
* infrastructure, so it gets a file of its own: the flag is read when the
* configuration module loads, and a suite cannot hold both answers at once.
*/
process.env.WEB_PUBLIC_STATUS = 'false';
const { closeDatabase, initDatabase } = await import('../src/database/index.js');
const { createHandler } = await import('../src/web/server.js');
describe('status page turned off', () => {
let app;
before(async () => {
initDatabase(':memory:');
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 call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('does not serve the page', async () => {
const response = await call('/status');
assert.equal(response.status, 404);
assert.doesNotMatch(await response.text(), /État des services/);
});
it('does not answer in JSON either', async () => {
assert.equal((await call('/api/status')).status, 404);
});
it('leaves the health probe alone', async () => {
assert.equal((await call('/api/health')).status, 200);
});
});
+214
View File
@@ -0,0 +1,214 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
/**
* Public status page (M19).
*
* The guild id is set before the modules that read it are loaded — hence the
* dynamic imports, the same arrangement the Gitea import test uses.
*/
process.env.DISCORD_GUILD_ID = '900000000000000000';
const GUILD = process.env.DISCORD_GUILD_ID;
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
const { createDeployment, finishDeployment } =
await import('../src/database/repositories/deploy-repository.js');
const { renderStatus } = await import('../src/web/services/status-render.js');
const { resetStatusCache, statusSnapshot } = await import('../src/web/services/status-service.js');
const { createHandler } = await import('../src/web/server.js');
const snapshot = (overrides = {}) => ({
bot: {
online: true,
state: 'ok',
uptimeMs: 3_600_000,
startedAt: new Date().toISOString(),
version: '1.2.3',
pingMs: 42,
},
environments: [],
releases: [],
links: {},
generatedAt: new Date().toISOString(),
...overrides,
});
const deploy = ({ environment, repository, status, releaseTag = null }) => {
const created = createDeployment({
guildId: GUILD,
targetName: environment,
repository,
environment,
releaseTag,
});
finishDeployment(created.id, { status });
return created;
};
describe('status page rendering', () => {
it('says everything works when the bot answers', () => {
const html = renderStatus(snapshot());
assert.match(html, /Tous les services fonctionnent/);
assert.match(html, /status-banner-ok/);
});
it('leads with the outage when the bot is down', () => {
const html = renderStatus(snapshot({ bot: { ...snapshot().bot, online: false, state: 'down' } }));
assert.match(html, /Le bot est hors ligne/);
assert.match(html, /status-banner-down/);
});
/** A green headline above a failed deployment is how a status page loses its point. */
it('refuses to look healthy while a deployment has failed', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: 'production',
repository: 'FWS/x',
status: 'failed',
tone: 'down',
releaseTag: null,
finishedAt: null,
},
],
}),
);
assert.match(html, /déploiement en échec/);
assert.match(html, /status-banner-busy/);
});
it('carries no script at all', () => {
assert.doesNotMatch(renderStatus(snapshot()), /<script/i);
});
it('refreshes itself without one', () => {
assert.match(renderStatus(snapshot()), /http-equiv="refresh"/);
});
it('escapes what it is given', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: '<img src=x onerror=alert(1)>',
repository: null,
status: 'success',
tone: 'ok',
releaseTag: null,
finishedAt: null,
},
],
}),
);
assert.doesNotMatch(html, /<img src=x/);
assert.match(html, /&lt;img src=x/);
});
it('keeps a private repository nameless rather than hiding the environment', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: 'staging',
repository: null,
status: 'success',
tone: 'ok',
releaseTag: 'v1',
finishedAt: null,
},
],
}),
);
assert.match(html, /staging/);
assert.match(html, /privé/);
});
it('points at the machine-readable version', () => {
assert.match(renderStatus(snapshot()), /\/api\/status/);
});
});
describe('status snapshot', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM deployments;');
resetStatusCache();
});
it('reports the bot as down when there is no client', async () => {
const data = await statusSnapshot({ client: null, startedAt: Date.now() });
assert.equal(data.bot.online, false);
assert.equal(data.bot.state, 'down');
});
it('keeps the last deployment of each environment', async () => {
deploy({ environment: 'production', repository: 'FWS/bot', status: 'success', releaseTag: 'v1.0.0' });
deploy({ environment: 'staging', repository: 'FWS/bot', status: 'failed' });
const { environments } = await statusSnapshot({ client: null });
const names = environments.map((entry) => entry.environment).sort();
assert.deepEqual(names, ['production', 'staging']);
assert.equal(environments.find((entry) => entry.environment === 'staging').tone, 'down');
});
it('names a tone for every deployment state', async () => {
deploy({ environment: 'production', repository: 'FWS/bot', status: 'running' });
const [entry] = (await statusSnapshot({ client: null })).environments;
assert.equal(entry.tone, 'busy');
});
});
describe('status over HTTP', () => {
let app;
before(async () => {
initDatabase(':memory:');
resetStatusCache();
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 call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('serves the page to a visitor with no session', async () => {
const response = await call('/status');
const html = await response.text();
assert.equal(response.status, 200);
assert.match(response.headers.get('content-type'), /text\/html/);
assert.match(html, /État des services/);
});
it('forbids scripts in its own headers', async () => {
const policy = (await call('/status')).headers.get('content-security-policy');
assert.match(policy, /script-src 'none'/);
});
it('answers the same in JSON, without a session', async () => {
const response = await call('/api/status');
const body = await response.json();
assert.equal(response.status, 200);
assert.equal(typeof body.bot.online, 'boolean');
assert.ok(Array.isArray(body.environments));
assert.ok(Array.isArray(body.releases));
});
it('tolerates a trailing slash', async () => {
assert.equal((await call('/status/')).status, 200);
});
});
+278
View File
@@ -0,0 +1,278 @@
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('terms-of-service').published);
assert.ok(getPageBySlug('privacy-policy').published);
});
it('marks the legal pages as protected', () => {
seedWiki();
assert.equal(getPageBySlug('privacy-policy').protected, true);
assert.equal(getPageBySlug('accueil').protected, false);
});
it('names the Swiss law it is written against', () => {
seedWiki();
const privacy = getPageBySlug('privacy-policy').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('terms-of-service').id, { content: 'Notre propre texte.' });
assert.equal(seedWiki(), 0);
assert.equal(getPageBySlug('terms-of-service').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 ('privacy-policy', 'accueil')");
assert.equal(seedWiki(), 1);
assert.ok(getPageBySlug('privacy-policy'));
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/terms-of-service');
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('serves the legal pages at the root, where platforms expect them', async () => {
for (const path of ['/terms-of-service', '/privacy-policy']) {
const response = await get(path);
assert.equal(response.status, 200, `${path} ne répond pas`);
assert.match(response.headers.get('content-type'), /text\/html/);
}
});
/**
* The point of the whole exercise: whoever checks these links before
* approving an application does not run scripts.
*/
it('delivers the legal text without any script', async () => {
const terms = await get('/terms-of-service').then((response) => response.text());
const privacy = await get('/privacy-policy').then((response) => response.text());
assert.match(terms, /droit suisse/, 'les conditions ne sont pas dans le HTML');
assert.match(privacy, /LPD/, 'la politique n’est pas dans le HTML');
assert.match(privacy, /PFPDT/);
assert.doesNotMatch(terms, /<script/i, 'la page embarque un script');
assert.doesNotMatch(privacy, /<script/i, 'la page embarque un script');
});
it('lets itself be indexed, unlike the dashboard', async () => {
const terms = await get('/terms-of-service').then((response) => response.text());
assert.match(terms, /name="robots" content="index, follow"/);
});
it('links both legal pages from every page of the wiki', async () => {
const index = await get('/wiki').then((response) => response.text());
assert.match(index, /href="\/terms-of-service"/);
assert.match(index, /href="\/privacy-policy"/);
});
it('searches without scripts, through a plain query string', async () => {
const results = await get('/wiki?q=confidentialit').then((response) => response.text());
assert.match(results, /résultat\(s\)/);
assert.match(results, /privacy-policy/);
});
it('answers 404 on an unknown page rather than a blank shell', async () => {
const response = await get('/wiki/inexistante');
assert.equal(response.status, 404);
assert.match(await response.text(), /introuvable/);
});
it('tells each page where it lives', async () => {
const body = await get('/api/wiki').then((response) => response.json());
const pages = body.categories.flatMap((category) => category.pages);
assert.equal(pages.find((page) => page.slug === 'terms-of-service').path, '/terms-of-service');
assert.equal(pages.find((page) => page.slug === 'privacy-policy').path, '/privacy-policy');
assert.equal(pages.find((page) => page.slug === 'accueil').path, '/wiki/accueil');
});
it('keeps an ordinary page under /wiki', async () => {
createPage({ slug: 'guide', title: 'Guide', content: 'x', published: true });
// Not a legal page: `/guide` belongs to the dashboard, not to the wiki.
assert.doesNotMatch(await get('/guide').then((r) => r.text()), /wiki-shell/);
assert.match(await get('/wiki/guide').then((r) => r.text()), /wiki-shell/);
});
it('keeps the administration behind the login', async () => {
assert.equal((await get('/api/wiki/admin')).status, 401);
});
it('serves the documentation rather than the dashboard shell', async () => {
const body = await get('/wiki/terms-of-service').then((response) => response.text());
assert.match(body, /wiki-shell/);
assert.doesNotMatch(body, /id="app"/);
});
});