diff --git a/.env.example b/.env.example index 1af6ff3..01a95b8 100644 --- a/.env.example +++ b/.env.example @@ -71,6 +71,37 @@ WEBHOOK_PATH=/webhooks/gitea # Shared secret configured in Gitea > Settings > Webhooks GITEA_WEBHOOK_SECRET= +# --- Tableau de bord web (M16) ----------------------------------------------- +# 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é. +WEB_ENABLED=false +# 127.0.0.1 derrière un reverse proxy installé sur la même machine. +# 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_PORT=3080 +# URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord. +# Doit correspondre exactement à une redirection déclarée dans le Developer Portal. +WEB_PUBLIC_URL=http://localhost:3080 +# Clé de signature des cookies de session (64 caractères hex). +# Générer avec : node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" +WEB_SESSION_SECRET= +WEB_SESSION_TTL_HOURS=12 +# Developer Portal > OAuth2 > Client Secret. Requis pour la connexion au tableau de bord. +DISCORD_CLIENT_SECRET= +# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord. +# À vider une fois le .env rempli. +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). +WEB_ALLOW_COMMAND_DEPLOYS=false +# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2). +WEB_ALLOW_RESTART=false +WEB_DEPLOY_TIMEOUT_MS=900000 +WEB_RATE_LIMIT_PER_MINUTE=240 + # --- SQLite (M1-T05) --------------------------------------------------------- DATABASE_PATH=./data/fws-bot.sqlite BACKUP_DIR=./data/backups diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..4e0adb3 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index fb83462..99d0462 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,30 @@ The project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Features +- **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]) - **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269]) - **voice:** _(feat)_ support several trigger channels with their own category ([836abea]) @@ -66,7 +90,36 @@ The project follows [Semantic Versioning](https://semver.org/). - **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe]) - **config:** _(feat)_ load and expose environment settings ([d1388b6]) +### Bug Fixes +- **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 +- **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]) - **changelog:** _(build)_ generate the changelog from the commit history ([478ae41]) - **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2]) diff --git a/README.en.md b/README.en.md index ea7fd09..ae2454d 100644 --- a/README.en.md +++ b/README.en.md @@ -161,6 +161,23 @@ Full template: [`.env.example`](.env.example). Default values in brackets. | `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea | | `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks | +### Web dashboard + +| Variable | Default | Description | +| --- | --- | --- | +| `WEB_ENABLED` | `false` | Serves the admin site from the bot process | +| `WEB_HOST` | `127.0.0.1` | Listening interface. Use `0.0.0.0` only behind an HTTPS reverse proxy | +| `WEB_PORT` | `3080` | Site port. When it equals `WEBHOOK_PORT`, a single HTTP server is started | +| `WEB_PUBLIC_URL` | — | Public URL of the site, base of the OAuth2 `/auth/callback` redirect | +| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret | +| `WEB_SESSION_SECRET` | — | Session signing key (64 hexadecimal characters) | +| `WEB_SESSION_TTL_HOURS` | `12` | Session lifetime before signing in again | +| `WEB_SETUP_TOKEN` | — | Bootstrap token opening the wizard without a Discord account | +| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Allows shell-command deploy targets (Owner only) | +| `WEB_ALLOW_RESTART` | `false` | Shows the bot restart button | +| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Delay after which a deployment is marked failed | +| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | API requests per minute and per IP address | + ### SQLite and links | Variable | Default | Description | @@ -299,7 +316,49 @@ Every command checks the FWS level **and** the matching Discord permission. The Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message. -## 6. Automations +## 6. Web dashboard + +The bot serves its own admin site: Gitea organization, repositories, releases, deployments, Discord server, logs and configuration. Full details: [`docs/web-dashboard.md`](docs/web-dashboard.md). + +No added dependency: `node:http` for the server, `node:sqlite` for the sessions, and a plain JavaScript front-end served as is. + +The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed. + +The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, tickets, voice, notifications. + +### 6.1 Getting started + +Without a `.env` the bot refuses to start, so the configuration wizard runs on its own, without connecting to Discord. + +```bash +npm run setup +``` + +The console prints the site URL and a temporary bootstrap token. Once the file is written, set `WEB_ENABLED=true` and start the bot as usual: the site then listens on `WEB_HOST:WEB_PORT`. + +So that members can sign in with Discord: copy the **Client Secret** from the portal into `DISCORD_CLIENT_SECRET`, add `/auth/callback` under **OAuth2 → Redirects** exactly as is, and generate `WEB_SESSION_SECRET`. + +### 6.2 Access and display modes + +The site reuses the access levels of the slash commands, derived from the Discord roles. Signing in requires at least the **Staff** level; **Dev** unlocks writes on repositories and deployments; **Owner** unlocks repository deletion, API tokens, backups and configuration. + +A **Simple / Advanced** switch hides or reveals the technical panels. It changes no permission: every call is checked again on the server. + +The pages update on their own: the server pushes every change over a `text/event-stream`, and an indicator at the bottom of the sidebar says where the connection stands. Nothing reloads while a dialog is open or a field has focus, and a periodic refresh takes over when the stream cannot get through. + +### 6.3 Configuration wizard + +Every `.env` variable is described once, in `src/web/services/env-schema.js`: the form, the explanations, the validation and the generated file all derive from it. + +The wizard tells you where to find each value, validates as you type, flags questionable combinations, generates the secrets, tests the Discord token and the Gitea token **before** writing anything, shows a preview of the file, backs the previous one up as `.env.bak-` then writes the new one with `600` permissions. An empty secret keeps the value already in place. + +### 6.4 Releases and deployments + +Publishing a release from the site builds its notes from the Conventional Commits, announces it in the releases channel and triggers the targets marked for automatic deployment. + +Three kinds of target: an HMAC-SHA256 signed **webhook** (recommended, nothing runs on the bot host), a **Gitea Actions workflow**, and a **shell command** — the latter stays blocked until `WEB_ALLOW_COMMAND_DEPLOYS` is enabled, and requires the Owner level. Every attempt leaves its full log in the history, successful or not. + +## 7. Automations - **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed). - **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age. @@ -309,7 +368,7 @@ Legend: ✅ working · expected errors are returned as ephemeral messages (`User - **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status. - **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call. -## 7. Architecture +## 8. Architecture Full details: [`docs/architecture.md`](docs/architecture.md). @@ -333,6 +392,9 @@ src/ │ └── voice/ # voice-service.js (several triggers, temporary channels, panel) ├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/ ├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── web/ # Dashboard: server.js · router.js · http.js +│ # auth/ (Discord OAuth2, sessions, access control) · api/ (one module per domain) +│ # services/ (.env schema, deployments) · public/ (front-end, no build) ├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls) └── utils/ # retry.js (exponential backoff) · cooldown.js ``` @@ -361,23 +423,23 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui - Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`. - Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**. -## 8. Database (SQLite) +## 9. Database (SQLite) - Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled. - Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`). -- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`. -- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — SQL queries never leave that layer. -- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) and `005-bot-statuses.sql` (bot statuses edited from a command) complete the initial schema. +- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run). +- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — SQL queries never leave that layer. +- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) `005-bot-statuses.sql` (bot statuses edited from a command) and `006-web-dashboard.sql` (sessions, API tokens, deploy targets and history) complete the initial schema. - The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`). -## 9. Logs +## 10. Logs - **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console. - Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr. - **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line. - Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`). -## 10. npm scripts +## 11. npm scripts | Script | Purpose | | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -387,13 +449,13 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui | `npm run db:init` | Creates the SQLite database and applies the migrations | | `npm run lint` / `npm run lint:fix` | ESLint (check / fix) | | `npm run format` / `npm run format:check` | Prettier (format / check) | -| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §12) | +| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §13) | | `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date | -| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | +| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` | When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels. -## 11. Security +## 12. Security - Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted. - No action is possible on a role or member positioned above the caller. @@ -402,14 +464,14 @@ When something goes wrong: run `npm run deploy:commands` after any command chang - Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only). - User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option). -## 12. Versioning and releases +## 13. Versioning and releases - **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states). - **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date. - Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`. - Generating it is part of the definition of done: the file is never edited by hand. -## 13. Contributing +## 14. Contributing The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here: @@ -441,7 +503,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it. - Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions. -## 14. Production checklist +## 15. Production checklist - [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention) - [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_) @@ -452,6 +514,9 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion - [ ] Enable the **Server Members** intent in the developer portal - [ ] Configure Gitea: least privilege token + webhook with a secret +- [ ] Configure the dashboard: `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` and the OAuth2 redirect declared in the portal +- [ ] Put an HTTPS reverse proxy in front of the site, then clear `WEB_SETUP_TOKEN` +- [ ] Declare the deploy targets and run a test deployment - [ ] Protect and back up the SQLite database - [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook - [ ] Test the API limits and the error paths @@ -459,7 +524,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - [ ] Fill in the official links and the screenshots (`assets/screenshots/`) - [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`) -## 15. Resources +## 16. Resources - FWS organisation: `[link to add]` - FWS Discord server: `[link to add]` @@ -467,6 +532,8 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - Gitea instance: `[link to add]` - FWS documentation: `[link to add]` - Technical documentation: [`docs/architecture.md`](docs/architecture.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) - Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_ - Instructions for AI agents: [`AGENTS.md`](AGENTS.md) diff --git a/README.md b/README.md index 1aca567..ac18f5b 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Choix assumés : **une seule dépendance runtime** (discord.js), aucun module na | **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks | | **`node:test`** | — | Tests unitaires intégrés (`node --test`) | | **ESLint** | ^9.30.0 (flat config) | Lint | +| **Front du tableau de bord** | — | JavaScript natif servi tel quel, aucune étape de build | + | **Prettier** | ^3.6.2 | Format | ## 2. Prérequis @@ -161,6 +163,23 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare | `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea | | `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks | +### Tableau de bord web + +| Variable | Défaut | Description | +| --- | --- | --- | +| `WEB_ENABLED` | `false` | Sert le site d'administration depuis le processus du bot | +| `WEB_HOST` | `127.0.0.1` | Interface d'écoute. `0.0.0.0` uniquement derrière un reverse proxy HTTPS | +| `WEB_PORT` | `3080` | Port du site. S'il vaut `WEBHOOK_PORT`, un seul serveur HTTP est démarré | +| `WEB_PUBLIC_URL` | — | URL publique du site, base de la redirection OAuth2 `/auth/callback` | +| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret | +| `WEB_SESSION_SECRET` | — | Clé de signature des sessions (64 caractères hexadécimaux) | +| `WEB_SESSION_TTL_HOURS` | `12` | Durée d'une session avant reconnexion | +| `WEB_SETUP_TOKEN` | — | Jeton d'amorçage ouvrant l'assistant sans compte Discord | +| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Autorise les cibles de déploiement de type commande shell (Owner) | +| `WEB_ALLOW_RESTART` | `false` | Affiche le bouton de redémarrage du bot | +| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Délai au-delà duquel un déploiement est en échec | +| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | Requêtes API par minute et par adresse IP | + ### SQLite et liens | Variable | Défaut | Description | @@ -299,7 +318,49 @@ Chaque commande vérifie le niveau FWS **et** la permission Discord correspondan Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique. -## 6. Automatisations +## 6. Tableau de bord web + +Le bot sert son propre site d'administration : organisation Gitea, dépôts, releases, déploiements, serveur Discord, journaux et configuration. Détail complet : [`docs/web-dashboard.md`](docs/web-dashboard.md). + +Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour les sessions, et un front en JavaScript natif servi tel quel. + +Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire. + +Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, tickets, vocaux, notifications. + +### 6.1 Démarrer + +Sans `.env`, le bot refuse de démarrer : l'assistant de configuration se lance donc seul, sans connexion à Discord. + +```bash +npm run setup +``` + +La console affiche l'URL du site et un jeton d'amorçage temporaire. Une fois le fichier écrit, mets `WEB_ENABLED=true` et démarre le bot normalement : le site écoute alors sur `WEB_HOST:WEB_PORT`. + +Pour que les membres puissent se connecter avec Discord : copie le **Client Secret** du portail dans `DISCORD_CLIENT_SECRET`, ajoute `/auth/callback` dans **OAuth2 → Redirects** à l'identique, et génère `WEB_SESSION_SECRET`. + +### 6.2 Accès et modes d'affichage + +Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff** ; **Dev** ouvre l'écriture sur les dépôts et les déploiements ; **Owner** ouvre la suppression de dépôt, les jetons d'API, les sauvegardes et la configuration. + +Un commutateur **Simple / Avancé** masque ou révèle les panneaux techniques. Il ne change aucun droit : chaque appel est revérifié côté serveur. + +Les pages se mettent à jour toutes seules : le serveur pousse chaque changement sur un flux `text/event-stream`, et un indicateur en bas de la barre latérale dit où en est la connexion. Rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus, et un rafraîchissement périodique prend le relais si le flux ne passe pas. + +### 6.3 Assistant de configuration + +Chaque variable du `.env` est décrite une seule fois, dans `src/web/services/env-schema.js` : le formulaire, les explications, la validation et le fichier généré en découlent tous. + +L'assistant indique où trouver chaque valeur, valide au fil de la frappe, signale les combinaisons douteuses, génère les secrets, teste le token Discord et le jeton Gitea **avant** d'écrire, montre un aperçu du fichier, sauvegarde l'ancien en `.env.bak-` puis écrit le nouveau avec les permissions `600`. Un secret laissé vide conserve la valeur déjà en place. + +### 6.4 Releases et déploiements + +Publier une release depuis le site génère ses notes à partir des commits Conventional Commits, l'annonce dans le salon des releases et déclenche les cibles marquées en déploiement automatique. + +Trois types de cible : **webhook** signé en HMAC-SHA256 (recommandé, rien ne s'exécute sur la machine du bot), **workflow Gitea Actions**, et **commande shell** — cette dernière reste bloquée tant que `WEB_ALLOW_COMMAND_DEPLOYS` n'est pas activé, et demande le niveau Owner. Chaque tentative laisse son journal complet dans l'historique, réussie comme échouée. + +## 7. Automatisations - **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés). - **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte. @@ -309,7 +370,7 @@ Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message - **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé. - **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API. -## 7. Architecture +## 8. Architecture Détails complets : [`docs/architecture.md`](docs/architecture.md). @@ -333,6 +394,9 @@ src/ │ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau) ├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/ ├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── web/ # Tableau de bord : server.js · router.js · http.js +│ # auth/ (OAuth2 Discord, sessions, contrôle d'accès) · api/ (un module par domaine) +│ # services/ (schéma du .env, déploiements) · public/ (front, sans build) ├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages) └── utils/ # retry.js (backoff exponentiel) · cooldown.js ``` @@ -361,55 +425,58 @@ Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en - Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`. - Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal. -## 8. Base de données (SQLite) +## 9. Base de données (SQLite) - Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées. - Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`). -- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`. -- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. -- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) et `005-bot-statuses.sql` (statuts du bot édités en commande) complètent le schéma initial. +- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`, `web_sessions` (sessions du tableau de bord, empreinte du cookie seulement), `web_api_tokens`, `deploy_targets` (cibles de déploiement), `deployments` (historique et journal de chaque exécution). +- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. +- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) `005-bot-statuses.sql` (statuts du bot édités en commande) et `006-web-dashboard.sql` (sessions, jetons d'API, cibles et historique de déploiement) complètent le schéma initial. - La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`). -## 9. Logs +## 10. Logs - Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console. - Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr. - **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée. - Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`). -## 10. Scripts npm +## 11. Scripts npm | Script | Rôle | | --- | --- | | `npm start` | Démarre le bot (`node src/index.js`) | | `npm run dev` | Démarre avec rechargement automatique (`node --watch`) | +| `npm run setup` | Lance l'assistant de configuration du `.env`, sans connexion Discord | | `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) | | `npm run db:init` | Crée la base SQLite et applique les migrations | | `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) | | `npm run format` / `npm run format:check` | Prettier (formater / vérifier) | -| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §12) | +| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §13) | | `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) | -| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | +| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` | En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles. -## 11. Sécurité +## 12. Sécurité - Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client. - Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur. - Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique). - Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery. - Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement). +- Tableau de bord : connexion Discord obligatoire (niveau Staff minimum), session en cookie `HttpOnly` dont seule l'empreinte est stockée, en-tête `X-Requested-With` exigé sur chaque écriture, vérification de l'origine, CSP restreinte à `self`, limitation de débit par adresse IP. +- Le site écoute sur `127.0.0.1` par défaut : place un reverse proxy HTTPS devant lui avant toute exposition. Les déploiements par commande shell et le redémarrage restent désactivés tant qu'on ne les active pas explicitement. - Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options). -## 12. Versionnage et releases +## 13. Versionnage et releases - **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer). - **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour. - Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`. - La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main. -## 13. Contribution +## 14. Contribution Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici : @@ -441,7 +508,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie. - Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions. -## 14. Checklist de mise en production +## 15. Checklist de mise en production - [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation) - [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*) @@ -452,6 +519,9 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - [ ] Configurer chaque salon vocal déclencheur (`/voice setup`) et vérifier création/suppression automatique - [ ] Activer l'intent **Server Members** dans le portail développeur - [ ] Configurer Gitea : token à moindre privilège + webhook avec secret +- [ ] Configurer le tableau de bord : `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` et la redirection OAuth2 déclarée dans le portail +- [ ] Placer un reverse proxy HTTPS devant le site, puis vider `WEB_SETUP_TOKEN` +- [ ] Déclarer les cibles de déploiement et lancer un déploiement de test - [ ] Protéger et sauvegarder la base SQLite - [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea - [ ] Tester les limites API et les chemins d'erreur @@ -459,7 +529,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`) - [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`) -## 15. Ressources +## 16. Ressources - Organisation FWS : `[lien à ajouter]` - Serveur Discord FWS : `[lien à ajouter]` @@ -467,6 +537,8 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - Instance Gitea : `[lien à ajouter]` - Documentation FWS : `[lien à ajouter]` - Documentation technique : [`docs/architecture.md`](docs/architecture.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) - Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)* - Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md) diff --git a/docs/architecture.md b/docs/architecture.md index bb48862..1d83202 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,11 +13,13 @@ fws-discordbot/ ├── logs/ # Logs techniques journaliers (ignoré par git) ├── scripts/ │ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur -│ └── init-database.js # Crée la base et applique les migrations +│ ├── init-database.js # Crée la base et applique les migrations +│ └── setup-server.js # Assistant de configuration du .env, sans Discord ├── src/ │ ├── index.js # Point d'entrée │ ├── config/ │ │ ├── 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 │ ├── core/ │ │ ├── client.js # Client Discord et intents @@ -34,6 +36,14 @@ fws-discordbot/ │ │ ├── migrations/ # Fichiers SQL numérotés │ │ └── repositories/ # Accès aux tables │ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea +│ ├── web/ # Tableau de bord : serveur, API, front (voir web-dashboard.md) +│ │ ├── server.js # Serveur HTTP, répartition et erreurs +│ │ ├── router.js # Routeur minimal `/api/x/:param` +│ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès +│ │ ├── api/ # Un module par domaine exposé +│ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements +│ │ ├── public/ # Front JavaScript natif, servi tel quel +│ │ └── public/wiki.* # Site de documentation public, servi sans session │ ├── ui/ # Embeds et boutons standardisés │ └── utils/ # Retry, cooldown… └── tests/ # Tests node:test @@ -58,6 +68,20 @@ export const once = false; // optionnel export async function execute(client, ...args) {} ``` +## Tableau de bord web + +Le bot sert un site d'administration (organisation, dépôts, releases, déploiements, configuration). Il réutilise les niveaux d'accès des commandes, déduits des rôles Discord, et ne démarre que si `WEB_ENABLED=true`. + +Aucune dépendance ajoutée : `node:http`, `node:sqlite`, `node:crypto`, et un front sans étape de build. Quand `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP sert le site et la route des webhooks. + +Une route se déclare avec son niveau minimum, appliqué par le serveur avant l'appel : + +```js +router.get('/api/repositories/:owner/:repo', handler, { access: ACCESS_LEVELS.STAFF }); +``` + +Détail complet : [`web-dashboard.md`](web-dashboard.md). + ## Intents Discord | Intent | Usage | Privilégié | @@ -73,7 +97,7 @@ export async function execute(client, ...args) {} ```bash npm install -cp .env.example .env # puis remplir les valeurs +npm run setup # assistant de configuration du .env, ou copier .env.example à la main npm run db:init npm run deploy:commands npm run dev diff --git a/docs/exploitation.md b/docs/exploitation.md new file mode 100644 index 0000000..89c959c --- /dev/null +++ b/docs/exploitation.md @@ -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://:@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 \ + --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. diff --git a/docs/web-dashboard.md b/docs/web-dashboard.md new file mode 100644 index 0000000..fea6f32 --- /dev/null +++ b/docs/web-dashboard.md @@ -0,0 +1,297 @@ +# Tableau de bord web + +Le bot sert lui-même un site d'administration : pilotage de l'organisation Gitea et de ses dépôts, gestion du serveur Discord, pipeline de releases et de déploiements, et un assistant qui écrit le fichier `.env` pas à pas. + +Aucune dépendance supplémentaire : `node:http` pour le serveur, `node:sqlite` pour les sessions, `node:crypto` pour les signatures, et un front en JavaScript natif servi tel quel (pas d'étape de build). + +## 1. Démarrer + +### Première installation, sans `.env` + +Le bot refuse de démarrer sans `DISCORD_TOKEN`. L'assistant de configuration se lance donc seul : + +```bash +npm install +npm run setup +``` + +La console affiche l'URL et un jeton d'amorçage à usage unique. Ouvre l'URL, colle le jeton, déroule l'assistant, enregistre. Puis : + +```bash +npm run db:init +npm run deploy:commands +npm run dev +``` + +### Site complet, bot configuré + +Mets `WEB_ENABLED=true` dans le `.env`, puis `npm start`. Le site écoute sur `WEB_HOST:WEB_PORT` (par défaut `127.0.0.1:3080`). + +Pour que les membres puissent se connecter avec Discord : + +1. Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`. +2. Toujours dans **OAuth2 → Redirects**, ajoute `/auth/callback`, à l'identique. +3. Génère `WEB_SESSION_SECRET` (l'assistant a un bouton pour ça). + +## 2. Qui a accès à quoi + +Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff**. + +| Niveau | Peut | +| --------- | --------------------------------------------------------------------------------------------------------- | +| **Staff** | Tout consulter, créer des issues, commenter, modérer, clôturer des tickets, publier une annonce | +| **Dev** | En plus : modifier les dépôts, merger, gérer branches et releases, lancer un déploiement, gérer les rôles | +| **Owner** | En plus : supprimer un dépôt, gérer collaborateurs et webhooks, jetons d'API, sauvegardes, `.env` | + +Un membre sans rôle Staff, Dev ou Owner ne peut pas ouvrir le site. Le propriétaire du serveur Discord est toujours Owner. + +### Modes Simple et Avancé + +Le commutateur en bas de la barre latérale masque ou révèle les panneaux techniques (identifiants bruts, journaux, réglages fins, colonnes secondaires). Le mode est retenu par navigateur, et n'a aucun effet sur les droits réels : le serveur vérifie chaque appel de son côté. + +## 3. Les pages + +| Page | Contenu | +| ---------------------- | ----------------------------------------------------------------------------------------------- | +| **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 | +| **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 | +| **Déploiements** | Cibles de déploiement et historique complet, avec le journal de chaque exécution | +| **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 | +| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués | +| **Paramètres** | Comportement du bot, connexions, sessions, jetons d'API, maintenance | +| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré | + +## 4. Assistant de configuration + +Le fichier `src/web/services/env-schema.js` décrit **chaque** variable : libellé, explication, type, valeur par défaut, marche à suivre pour l'obtenir. L'assistant, la validation et le `.env` généré en découlent tous. Ajouter une variable au bot, c'est l'ajouter là et nulle part ailleurs. + +L'assistant : + +- explique chaque étape (où cliquer dans le Developer Portal, quelles portées cocher dans Gitea) ; +- valide au fil de la frappe et signale les combinaisons douteuses (webhooks sans secret, site exposé sans HTTPS) ; +- génère les secrets aléatoires sur demande ; +- teste le token Discord et le jeton Gitea **avant** d'écrire quoi que ce soit ; +- montre un aperçu du fichier et la liste des changements en attente ; +- sauvegarde l'ancien `.env` en `.env.bak-` puis écrit le nouveau en `chmod 600` ; +- conserve les variables qu'il ne connaît pas plutôt que de les perdre. + +Un secret laissé vide signifie « garde la valeur actuelle » : impossible d'effacer un token par inadvertance. Les secrets ne repartent jamais vers le navigateur — seul leur statut (renseigné ou non) est envoyé. + +Les valeurs du `.env` ne sont lues qu'au démarrage : l'assistant indique quelles modifications demandent un redémarrage. + +## 5. Releases et déploiements + +### Publier + +Depuis la page **Releases** : choisis le dépôt, le tag et la branche cible. Le bouton **Générer les notes** lit les commits depuis la release précédente et les regroupe comme `scripts/generate-changelog.js` : nouveautés, corrections, performance, autres changements, avec un bloc « changements incompatibles » pour les commits marqués `!` ou `BREAKING CHANGE`. + +Publier une release non brouillon annonce la version dans le salon `releases` et déclenche les cibles marquées « déploiement automatique ». + +### Cibles de déploiement + +| Type | Ce qui se passe | Risque | +| ----------------- | ----------------------------------------------------------------------- | ---------------------------------------- | +| **Webhook** | POST JSON signé HMAC-SHA256 vers ton serveur, en-tête `X-FWS-Signature` | Faible — rien ne s'exécute chez le bot | +| **Gitea Actions** | Déclenche un workflow `workflow_dispatch` | Faible | +| **Commande** | Exécute une commande shell sur la machine du bot | **Élevé** — exécution de code arbitraire | + +Les cibles « commande » sont doublement verrouillées : `WEB_ALLOW_COMMAND_DEPLOYS=true` **et** niveau Owner. Elles restent désactivées par défaut. + +Corps envoyé à un webhook : + +```json +{ + "deploymentId": 12, + "repository": "FWS/FWS-Arch", + "environment": "production", + "target": "production-web", + "ref": "main", + "releaseTag": "v1.2.0", + "triggeredBy": "123456789012345678", + "source": "web" +} +``` + +Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en hexadécimal, comparé en temps constant. + +Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec). + +## 6. Mise à jour automatique + +Les pages suivent le bot en direct : aucun rafraîchissement manuel n'est nécessaire. + +Le serveur tient un flux `text/event-stream` sur `GET /api/events`, un par onglet ouvert. Il y publie : + +- **chaque écriture réussie** de l'API, étiquetée selon la page concernée (`deployments`, `gitea`, `discord`, `community`, `settings`) — une écriture rejetée ne déclenche rien ; +- **l'avancement des déploiements**, au démarrage puis à l'arrivée du résultat ; +- **les webhooks Gitea** reçus, dès qu'ils sont validés ; +- un **tick** toutes les 15 secondes, et un battement de cœur toutes les 25 secondes qui empêche les proxys de fermer un flux inactif. + +Côté navigateur, un seul `EventSource` sert tout le tableau de bord, et chaque page ne réagit qu'aux sujets qui la concernent. L'indicateur en bas de la barre latérale dit où en est la connexion. + +Trois garde-fous, parce qu'un rafraîchissement qui tombe au mauvais moment est pire qu'une donnée un peu vieille : + +- rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus — le rafraîchissement est rejoué ensuite ; +- une rafale d'écritures ne produit qu'un seul rechargement ; +- l'onglet en arrière-plan ferme son flux et le rouvre au retour. + +Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — un rafraîchissement périodique prend le relais automatiquement, et l'indicateur passe en orange. La page Serveur Discord est volontairement hors du tick : lister les membres appelle l'API Discord, elle ne se rafraîchit que sur un vrai changement. + +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. 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, 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`. + +## 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. + +```bash +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. + +## 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. +- **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`. +- **Écritures.** Toute requête autre qu'une lecture exige l'en-tête `X-Requested-With: fws-dashboard`, que le navigateur ne peut pas forger depuis un autre site, plus une vérification de l'origine. +- **En-têtes.** CSP restreinte à `self`, `X-Frame-Options: DENY`, `nosniff`, aucune ressource tierce. +- **Limitation de débit.** `WEB_RATE_LIMIT_PER_MINUTE` requêtes par adresse IP et par minute. +- **Secrets.** Jamais renvoyés au navigateur, jamais écrits dans les logs (`maskSecrets`). +- **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. + +## 13. Fonctionnement interne + +```text +src/web/ +├── server.js # Serveur HTTP, répartition, gestion des erreurs, limitation de débit +├── router.js # Routeur : motifs `/api/x/:param`, 404 et 405 +├── http.js # Réponses JSON, corps, cookies, fichiers statiques, en-têtes de sécurité +├── setup-state.js # Jeton d'amorçage de l'assistant +├── auth/ +│ ├── discord-oauth.js # Flux OAuth2 et calcul du niveau d'accès +│ ├── session.js # Sessions signées, jetons d'API, protection anti-CSRF +│ ├── guard.js # Contrôle d'accès par route +│ └── routes.js # /auth/login, /auth/callback, /api/me +├── api/ # Un module par domaine fonctionnel +├── services/ +│ ├── env-schema.js # Description documentée de chaque variable +│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env +│ ├── 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) + ├── index.html + ├── styles.css + ├── app.js # Shell, navigation, routage par fragment + ├── core/ # dom.js, api.js, ui.js, live.js, nav.js, palette.js + └── views/ # Une vue par page +``` + +Une route se déclare ainsi : + +```js +router.get( + '/api/repositories/:owner/:repo', + async ({ params, query, body, actor, context }) => { + return { fullName: `${params.owner}/${params.repo}` }; + }, + { access: ACCESS_LEVELS.STAFF }, +); +``` + +Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le corps JSON, puis sérialise la valeur retournée. Une `HttpError` fixe le code ; une `UserFacingError` devient un 400 ; toute autre erreur est journalisée et remplacée par un message générique. + +### Partage de port avec les webhooks + +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. + +## 14. Dépannage + +| Symptôme | Cause probable | +| ---------------------------------------------- | ------------------------------------------------------------------------------- | +| `state-mismatch` à la connexion | Cookies bloqués, ou plus de 10 minutes entre le clic et le retour | +| `exchange-failed` | L'URL de redirection du portail ne correspond pas exactement à `WEB_PUBLIC_URL` | +| `insufficient-level` | Le compte n'a ni rôle Staff, ni Dev, ni Owner sur le serveur | +| Déconnexion à chaque redémarrage | `WEB_SESSION_SECRET` n'est pas défini | +| « Gitea n'est pas configuré » | `GITEA_URL` ou `GITEA_TOKEN` manquant — teste le jeton depuis les paramètres | +| Onglet Actions vide | Gitea Actions désactivé sur le dépôt, ou Gitea antérieur à 1.20 | +| Les modifications du `.env` restent sans effet | Le fichier n'est lu qu'au démarrage : redémarre le bot | diff --git a/eslint.config.js b/eslint.config.js index 04fcf2c..a331612 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,5 +17,10 @@ export default [ eqeqeq: ['error', 'always'], }, }, + { + // The dashboard front-end runs in the browser, not in Node (M16-T11). + files: ['src/web/public/**/*.js'], + languageOptions: { globals: globals.browser }, + }, prettier, ]; diff --git a/package.json b/package.json index 5c5eaa1..2219944 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "scripts": { "start": "node src/index.js", "dev": "node --watch src/index.js", + "setup": "node scripts/setup-server.js", "deploy:commands": "node scripts/deploy-commands.js", "db:init": "node scripts/init-database.js", "changelog": "node scripts/generate-changelog.js", diff --git a/scripts/setup-server.js b/scripts/setup-server.js new file mode 100644 index 0000000..d3efa57 --- /dev/null +++ b/scripts/setup-server.js @@ -0,0 +1,47 @@ +#!/usr/bin/env node +import { env } from '../src/config/env.js'; +import { logger } from '../src/core/logger.js'; +import { initDatabase } from '../src/database/index.js'; +import { startWebServer } from '../src/web/server.js'; +import { generateRuntimeSetupToken, hasSetupToken } from '../src/web/setup-state.js'; + +/** + * Starts the configuration wizard alone, without connecting to Discord (M16-T09). + * + * This is the entry point for a fresh clone: the bot itself refuses to start + * without `DISCORD_TOKEN`, so the `.env` has to be writable from somewhere else. + * + * Usage: npm run setup + */ + +// The wizard stores its session in SQLite, so the database must exist. +initDatabase(); + +const token = env.web.setupToken || generateRuntimeSetupToken(); +const url = + env.web.publicUrl || `http://${env.web.host === '0.0.0.0' ? 'localhost' : env.web.host}:${env.web.port}`; + +const server = startWebServer({ client: null, setupOnly: true }); + +logger.info('Configuration wizard started'); +console.log(` +┌──────────────────────────────────────────────────────────────────────┐ +│ Assistant de configuration FWS-Bot │ +└──────────────────────────────────────────────────────────────────────┘ + + Ouvre ${url}/#/setup + Jeton ${token} + ${env.web.setupToken ? 'Ce jeton vient de WEB_SETUP_TOKEN.' : 'Ce jeton est temporaire : il change à chaque lancement.'} + + Une fois le .env enregistré : Ctrl+C, puis npm run db:init, + npm run deploy:commands et npm run dev. +`); + +if (!hasSetupToken()) logger.warn('No setup token available, the wizard cannot be opened'); + +const shutdown = () => { + server.close(); + process.exit(0); +}; +process.once('SIGINT', shutdown); +process.once('SIGTERM', shutdown); diff --git a/src/commands/moderation/ban.js b/src/commands/moderation/ban.js index 61cfa6f..0a5f92f 100644 --- a/src/commands/moderation/ban.js +++ b/src/commands/moderation/ban.js @@ -1,8 +1,10 @@ import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ACCESS_LEVELS } from '../../config/constants.js'; +import { readSetting } from '../../config/guild-settings.js'; import { assertModerationTarget, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -27,16 +29,17 @@ export const data = new SlashCommandBuilder() export async function execute(interaction) { const user = interaction.options.getUser('user', true); 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); if (member) { assertModerationTarget(interaction, member); - await member - .send({ - embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); + await notifyTarget(member, { + embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], + }); } await interaction.deferReply({ flags: MessageFlags.Ephemeral }); diff --git a/src/commands/moderation/kick.js b/src/commands/moderation/kick.js index c42da02..e073eba 100644 --- a/src/commands/moderation/kick.js +++ b/src/commands/moderation/kick.js @@ -4,6 +4,7 @@ import { assertModerationTarget, fetchTargetMember, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -26,11 +27,9 @@ export async function execute(interaction) { assertModerationTarget(interaction, target); await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], + }); await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`); await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); diff --git a/src/commands/moderation/mute.js b/src/commands/moderation/mute.js index bb9b120..bbb6039 100644 --- a/src/commands/moderation/mute.js +++ b/src/commands/moderation/mute.js @@ -1,10 +1,12 @@ import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ACCESS_LEVELS } from '../../config/constants.js'; +import { readSetting } from '../../config/guild-settings.js'; import { assertModerationTarget, fetchTargetMember, formatDuration, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -20,7 +22,6 @@ export const data = new SlashCommandBuilder() option .setName('minutes') .setDescription('Durée de la sanction, en minutes') - .setRequired(true) .setMinValue(1) .setMaxValue(40_320), ) @@ -29,7 +30,9 @@ export const data = new SlashCommandBuilder() /** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */ export async function execute(interaction) { 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 durationMs = minutes * 60_000; @@ -45,11 +48,9 @@ export async function execute(interaction) { reason, durationMs, }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], + }); await interaction.editReply({ embeds: [ diff --git a/src/commands/moderation/warn.js b/src/commands/moderation/warn.js index 0c79d3f..f4ab60f 100644 --- a/src/commands/moderation/warn.js +++ b/src/commands/moderation/warn.js @@ -5,6 +5,7 @@ import { assertModerationTarget, fetchTargetMember, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.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 }); const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' }); - await target - .send({ - embeds: [ - targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ - name: 'Avertissements', - value: String(total), - }), - ], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [ + targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ + name: 'Avertissements', + value: String(total), + }), + ], + }); await interaction.editReply({ embeds: [ diff --git a/src/config/env.js b/src/config/env.js index e08c0c7..44275e0 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -79,6 +79,26 @@ export const env = Object.freeze({ secret: read('GITEA_WEBHOOK_SECRET'), }, + web: { + enabled: readBool('WEB_ENABLED'), + host: read('WEB_HOST', '127.0.0.1'), + port: readInt('WEB_PORT', 3080), + publicUrl: read('WEB_PUBLIC_URL', '').replace(/\/+$/, ''), + sessionSecret: read('WEB_SESSION_SECRET'), + sessionTtlHours: readInt('WEB_SESSION_TTL_HOURS', 12), + oauthClientSecret: read('DISCORD_CLIENT_SECRET'), + setupToken: read('WEB_SETUP_TOKEN'), + // Running shell commands from a browser is the most dangerous capability of the + // dashboard, so it stays off until it is explicitly enabled (M16-T06). + allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'), + 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), + rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240), + }, + database: { path: read('DATABASE_PATH', './data/fws-bot.sqlite'), backupDir: read('BACKUP_DIR', './data/backups'), @@ -93,7 +113,14 @@ export const env = Object.freeze({ }); /** Values that must never appear in Discord messages or logs. */ -export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean); +export const secrets = [ + env.discord.token, + env.gitea.token, + env.webhook.secret, + env.web.sessionSecret, + env.web.oauthClientSecret, + env.web.setupToken, +].filter(Boolean); export function assertRequiredEnv(keys) { const missing = keys.filter((key) => !read(key)); diff --git a/src/config/guild-settings.js b/src/config/guild-settings.js new file mode 100644 index 0000000..99c48cd --- /dev/null +++ b/src/config/guild-settings.js @@ -0,0 +1,250 @@ +import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js'; +import { env } from './env.js'; + +/** + * Settings a server can change without touching the `.env` (M16-T13). + * + * Single source of truth: the form, the validation and the values the services + * read all come from here. A setting that is not read by anything has no + * business being in this list — a switch that does nothing is worse than no + * switch at all. + */ + +export const SETTING_SECTIONS = Object.freeze([ + { + id: 'welcome', + title: 'Arrivées et départs', + summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.', + }, + { id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' }, + { id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' }, + { + id: 'voice', + title: 'Salons vocaux', + summary: 'Salons temporaires créés par les déclencheurs.', + }, + { id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' }, + { id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' }, +]); + +export const GUILD_SETTINGS = Object.freeze([ + // --- Arrivées et départs --------------------------------------------------- + { + key: 'welcome.enabled', + section: 'welcome', + label: 'Message de bienvenue', + help: 'Publier un message dans le salon d’accueil à chaque arrivée.', + type: 'bool', + default: true, + }, + { + key: 'welcome.message', + section: 'welcome', + label: 'Texte de bienvenue', + help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.', + type: 'text', + default: 'Bienvenue sur le serveur **{server}** !', + maxLength: 500, + }, + { + key: 'welcome.showRules', + section: 'welcome', + label: 'Rappeler le règlement', + help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.', + type: 'bool', + default: true, + }, + { + key: 'welcome.directMessage', + section: 'welcome', + label: 'Message privé de bienvenue', + help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.', + type: 'bool', + default: false, + }, + { + key: 'members.autoRole', + section: 'welcome', + label: 'Attribuer le rôle d’arrivée', + help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.', + type: 'bool', + default: true, + }, + { + key: 'departure.announce', + section: 'welcome', + label: 'Annoncer les départs', + help: 'Publie une ligne dans les logs quand un membre quitte le serveur.', + type: 'bool', + default: true, + }, + + // --- Modération ------------------------------------------------------------ + { + key: 'moderation.dmTarget', + section: 'moderation', + label: 'Prévenir le membre sanctionné', + help: 'Envoie un message privé expliquant la sanction et son motif.', + type: 'bool', + default: true, + }, + { + key: 'moderation.defaultMuteMinutes', + section: 'moderation', + label: 'Durée d’exclusion par défaut (min)', + help: 'Proposée quand `/mute` est lancé sans durée.', + type: 'int', + default: 60, + min: 1, + max: 40_320, + }, + { + key: 'moderation.banDeleteMessageHours', + section: 'moderation', + label: 'Messages supprimés au bannissement (h)', + help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.', + type: 'int', + default: 0, + min: 0, + max: 168, + advanced: true, + }, + + // --- Tickets --------------------------------------------------------------- + { + key: 'tickets.deleteChannelOnClose', + section: 'tickets', + label: 'Supprimer le salon à la clôture', + help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.', + type: 'bool', + default: true, + }, + + // --- Salons vocaux --------------------------------------------------------- + { + key: 'voice.adoptOrphans', + section: 'voice', + label: 'Récupérer les salons orphelins', + help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.', + type: 'bool', + default: true, + }, + + // --- Notifications --------------------------------------------------------- + { + key: 'notifications.mentionRoleId', + section: 'notifications', + label: 'Rôle à mentionner', + help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.', + type: 'snowflake', + default: '', + advanced: true, + }, + + // --- Tableau de bord ------------------------------------------------------- + { + key: 'deploy.requireConfirmation', + section: 'interface', + label: 'Confirmation avant déploiement', + help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.', + type: 'bool', + default: true, + }, + { + key: 'web.defaultMode', + section: 'interface', + label: 'Mode d’affichage par défaut', + help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.', + type: 'enum', + options: ['simple', 'advanced'], + default: 'simple', + }, +]); + +export const SETTING_BY_KEY = Object.freeze( + Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])), +); + +/** Coerces a stored value to the declared type, falling back on the default. */ +function coerce(setting, value) { + if (value === null || value === undefined) return setting.default; + + switch (setting.type) { + case 'bool': + return Boolean(value); + case 'int': { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed)) return setting.default; + if (setting.min !== undefined && parsed < setting.min) return setting.min; + if (setting.max !== undefined && parsed > setting.max) return setting.max; + return parsed; + } + case 'enum': + return setting.options.includes(value) ? value : setting.default; + default: + return String(value); + } +} + +/** + * Reads a setting. Never throws: called from event handlers that must keep + * working even when the database is momentarily unavailable. + */ +export function readSetting(key, guildId = env.discord.guildId) { + const setting = SETTING_BY_KEY[key]; + if (!setting) throw new Error(`Unknown guild setting: ${key}`); + return coerce(setting, resolveSetting(guildId, key, setting.default)); +} + +/** Validates then stores a setting. Returns the stored value. */ +export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) { + const setting = SETTING_BY_KEY[key]; + if (!setting) throw new Error(`Unknown guild setting: ${key}`); + + const message = validateSetting(key, value); + if (message) throw new Error(message); + + const stored = coerce(setting, value); + setSetting(guildId, key, stored, updatedBy); + return stored; +} + +/** Returns null when the value is acceptable, a French message otherwise. */ +export function validateSetting(key, value) { + const setting = SETTING_BY_KEY[key]; + if (!setting) return `Réglage inconnu : ${key}`; + + switch (setting.type) { + case 'bool': + return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.'; + case 'int': { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.'; + if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`; + if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`; + return null; + } + case 'enum': + return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`; + case 'snowflake': { + const text = String(value ?? '').trim(); + return text === '' || /^\d{17,20}$/.test(text) + ? null + : 'Un identifiant Discord est composé de 17 à 20 chiffres.'; + } + default: { + const text = String(value ?? ''); + if (setting.maxLength && text.length > setting.maxLength) { + return `${setting.maxLength} caractères maximum.`; + } + return null; + } + } +} + +/** Every setting with its current value, for the settings page. */ +export function allSettings(guildId = env.discord.guildId) { + return Object.fromEntries( + GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]), + ); +} diff --git a/src/database/migrations/006-web-dashboard.sql b/src/database/migrations/006-web-dashboard.sql new file mode 100644 index 0000000..53ff029 --- /dev/null +++ b/src/database/migrations/006-web-dashboard.sql @@ -0,0 +1,80 @@ +-- Web dashboard: sessions, machine tokens, deploy targets and deployments (M16) + +-- Browser sessions created by the Discord OAuth2 login (M16-T02). +-- Only the hash of the cookie value is stored, so a database dump cannot be replayed. +CREATE TABLE IF NOT EXISTS web_sessions ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + user_id TEXT, + username TEXT, + display_name TEXT, + avatar TEXT, + access_level INTEGER NOT NULL DEFAULT 0, + source TEXT NOT NULL DEFAULT 'discord' CHECK (source IN ('discord', 'setup', 'token')), + ip TEXT, + user_agent TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_seen_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at); +CREATE INDEX IF NOT EXISTS idx_web_sessions_user ON web_sessions (user_id); + +-- Long lived tokens for scripts and CI calling the dashboard API (M16-T03). +CREATE TABLE IF NOT EXISTS web_api_tokens ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + access_level INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_used_at TEXT, + expires_at TEXT, + revoked_at TEXT +); + +-- Where a release can be deployed: a signed webhook, a local command or a Gitea Action (M16-T06). +CREATE TABLE IF NOT EXISTS deploy_targets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL DEFAULT 'production', + kind TEXT NOT NULL CHECK (kind IN ('webhook', 'command', 'gitea-action')), + config TEXT NOT NULL DEFAULT '{}', + auto_deploy INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_deploy_targets_name ON deploy_targets (guild_id, name); +CREATE INDEX IF NOT EXISTS idx_deploy_targets_repo ON deploy_targets (guild_id, repository); + +-- One row per deployment attempt. `target_name` is denormalised so the history +-- survives the deletion of its target (M16-T07). +CREATE TABLE IF NOT EXISTS deployments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + target_id INTEGER REFERENCES deploy_targets (id) ON DELETE SET NULL, + target_name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL, + ref TEXT, + release_tag TEXT, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'running', 'success', 'failed', 'cancelled')), + source TEXT NOT NULL DEFAULT 'web', + triggered_by TEXT, + log TEXT, + error TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + started_at TEXT, + finished_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_deployments_target ON deployments (guild_id, target_id, id DESC); +CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments (status, id DESC); diff --git a/src/database/migrations/007-wiki.sql b/src/database/migrations/007-wiki.sql new file mode 100644 index 0000000..31c8810 --- /dev/null +++ b/src/database/migrations/007-wiki.sql @@ -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); diff --git a/src/database/migrations/008-projects.sql b/src/database/migrations/008-projects.sql new file mode 100644 index 0000000..76c11dc --- /dev/null +++ b/src/database/migrations/008-projects.sql @@ -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); diff --git a/src/database/migrations/009-legal-slugs.sql b/src/database/migrations/009-legal-slugs.sql new file mode 100644 index 0000000..bc67d1f --- /dev/null +++ b/src/database/migrations/009-legal-slugs.sql @@ -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'; diff --git a/src/database/repositories/deploy-repository.js b/src/database/repositories/deploy-repository.js new file mode 100644 index 0000000..40b0fcf --- /dev/null +++ b/src/database/repositories/deploy-repository.js @@ -0,0 +1,176 @@ +import { getDatabase } from '../index.js'; + +/** Deploy targets and deployment history of the release pipeline (M16-T06 / M16-T07). */ + +const parseTarget = (row) => + row + ? { + ...row, + config: JSON.parse(row.config), + auto_deploy: Boolean(row.auto_deploy), + enabled: Boolean(row.enabled), + } + : null; + +export function createTarget({ + guildId, + name, + repository, + environment = 'production', + kind, + config = {}, + autoDeploy = false, + enabled = true, + createdBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deploy_targets + (guild_id, name, repository, environment, kind, config, auto_deploy, enabled, created_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + guildId, + name, + repository, + environment, + kind, + JSON.stringify(config), + autoDeploy ? 1 : 0, + enabled ? 1 : 0, + createdBy, + ); + return getTarget(Number(lastInsertRowid)); +} + +export function getTarget(id) { + return parseTarget(getDatabase().prepare('SELECT * FROM deploy_targets WHERE id = ?').get(id) ?? null); +} + +export function listTargets({ guildId, repository = null } = {}) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + return getDatabase() + .prepare(`SELECT * FROM deploy_targets WHERE ${clauses.join(' AND ')} ORDER BY environment, name`) + .all(...params) + .map(parseTarget); +} + +/** Targets eligible for an automatic deployment when a release is published (M16-T08). */ +export function listAutoTargets({ guildId, repository }) { + return getDatabase() + .prepare( + `SELECT * FROM deploy_targets + WHERE guild_id = ? AND repository = ? AND auto_deploy = 1 AND enabled = 1 + ORDER BY environment, name`, + ) + .all(guildId, repository) + .map(parseTarget); +} + +const UPDATABLE = Object.freeze({ + name: (value) => value, + repository: (value) => value, + environment: (value) => value, + kind: (value) => value, + config: (value) => JSON.stringify(value), + auto_deploy: (value) => (value ? 1 : 0), + enabled: (value) => (value ? 1 : 0), +}); + +export function updateTarget(id, patch) { + const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE); + if (entries.length === 0) return getTarget(id); + + const assignments = entries.map(([key]) => `${key} = ?`).join(', '); + const values = entries.map(([key, value]) => UPDATABLE[key](value)); + getDatabase() + .prepare(`UPDATE deploy_targets SET ${assignments}, updated_at = datetime('now') WHERE id = ?`) + .run(...values, id); + return getTarget(id); +} + +export function removeTarget(id) { + return getDatabase().prepare('DELETE FROM deploy_targets WHERE id = ?').run(id).changes; +} + +export function createDeployment({ + guildId, + targetId = null, + targetName, + repository, + environment, + ref = null, + releaseTag = null, + source = 'web', + triggeredBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deployments + (guild_id, target_id, target_name, repository, environment, ref, release_tag, source, triggered_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, targetId, targetName, repository, environment, ref, releaseTag, source, triggeredBy); + return getDeployment(Number(lastInsertRowid)); +} + +export function getDeployment(id) { + return getDatabase().prepare('SELECT * FROM deployments WHERE id = ?').get(id) ?? null; +} + +export function listDeployments({ guildId, targetId = null, repository = null, status = null, limit = 30 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (targetId) { + clauses.push('target_id = ?'); + params.push(targetId); + } + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + if (status) { + clauses.push('status = ?'); + params.push(status); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM deployments WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function markRunning(id) { + return getDatabase() + .prepare("UPDATE deployments SET status = 'running', started_at = datetime('now') WHERE id = ?") + .run(id).changes; +} + +export function finishDeployment(id, { status, log = null, error = null }) { + return getDatabase() + .prepare( + `UPDATE deployments SET status = ?, log = ?, error = ?, finished_at = datetime('now') WHERE id = ?`, + ) + .run(status, log, error, id).changes; +} + +/** Counts per status, used by the dashboard tiles. */ +export function countByStatus(guildId) { + return getDatabase() + .prepare('SELECT status, COUNT(*) AS count FROM deployments WHERE guild_id = ? GROUP BY status') + .all(guildId); +} + +export function lastDeploymentPerEnvironment(guildId) { + return getDatabase() + .prepare( + `SELECT environment, repository, status, release_tag, finished_at, MAX(id) AS id + FROM deployments WHERE guild_id = ? GROUP BY environment, repository ORDER BY environment`, + ) + .all(guildId); +} diff --git a/src/database/repositories/project-repository.js b/src/database/repositories/project-repository.js new file mode 100644 index 0000000..5a73bf7 --- /dev/null +++ b/src/database/repositories/project-repository.js @@ -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); +} diff --git a/src/database/repositories/web-session-repository.js b/src/database/repositories/web-session-repository.js new file mode 100644 index 0000000..c0dcc89 --- /dev/null +++ b/src/database/repositories/web-session-repository.js @@ -0,0 +1,107 @@ +import { getDatabase } from '../index.js'; + +/** Browser sessions and machine tokens of the web dashboard (M16-T02 / M16-T03). */ + +export function createSession({ + id, + tokenHash, + userId = null, + username = null, + displayName = null, + avatar = null, + accessLevel = 0, + source = 'discord', + ip = null, + userAgent = null, + expiresAt, +}) { + getDatabase() + .prepare( + `INSERT INTO web_sessions + (id, token_hash, user_id, username, display_name, avatar, access_level, source, ip, user_agent, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(id, tokenHash, userId, username, displayName, avatar, accessLevel, source, ip, userAgent, expiresAt); + return getSession(id); +} + +export function getSession(id) { + return getDatabase().prepare('SELECT * FROM web_sessions WHERE id = ?').get(id) ?? null; +} + +/** Only returns sessions that have not expired, so callers never have to check. */ +export function getLiveSessionByHash(tokenHash) { + return ( + getDatabase() + .prepare("SELECT * FROM web_sessions WHERE token_hash = ? AND expires_at > datetime('now')") + .get(tokenHash) ?? null + ); +} + +export function touchSession(id) { + return getDatabase().prepare("UPDATE web_sessions SET last_seen_at = datetime('now') WHERE id = ?").run(id) + .changes; +} + +export function deleteSession(id) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE id = ?').run(id).changes; +} + +export function deleteSessionsOfUser(userId) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE user_id = ?').run(userId).changes; +} + +export function listSessions(limit = 50) { + return getDatabase() + .prepare( + `SELECT id, user_id, username, display_name, avatar, access_level, source, ip, user_agent, + created_at, last_seen_at, expires_at + FROM web_sessions WHERE expires_at > datetime('now') ORDER BY last_seen_at DESC LIMIT ?`, + ) + .all(limit); +} + +export function purgeExpiredSessions() { + return getDatabase().prepare("DELETE FROM web_sessions WHERE expires_at <= datetime('now')").run().changes; +} + +export function createApiToken({ name, tokenHash, prefix, accessLevel, createdBy = null, expiresAt = null }) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO web_api_tokens (name, token_hash, prefix, access_level, created_by, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(name, tokenHash, prefix, accessLevel, createdBy, expiresAt); + return Number(lastInsertRowid); +} + +export function getLiveApiTokenByHash(tokenHash) { + return ( + getDatabase() + .prepare( + `SELECT * FROM web_api_tokens + WHERE token_hash = ? AND revoked_at IS NULL + AND (expires_at IS NULL OR expires_at > datetime('now'))`, + ) + .get(tokenHash) ?? null + ); +} + +export function touchApiToken(id) { + getDatabase().prepare("UPDATE web_api_tokens SET last_used_at = datetime('now') WHERE id = ?").run(id); +} + +export function listApiTokens() { + return getDatabase() + .prepare( + `SELECT id, name, prefix, access_level, created_by, created_at, last_used_at, expires_at, revoked_at + FROM web_api_tokens ORDER BY id DESC`, + ) + .all(); +} + +export function revokeApiToken(id) { + return getDatabase() + .prepare("UPDATE web_api_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL") + .run(id).changes; +} diff --git a/src/database/repositories/wiki-repository.js b/src/database/repositories/wiki-repository.js new file mode 100644 index 0000000..bbb22a7 --- /dev/null +++ b/src/database/repositories/wiki-repository.js @@ -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); +} diff --git a/src/events/client-ready.js b/src/events/client-ready.js index 964e69a..1bb0d4b 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -2,7 +2,11 @@ import { Events } from 'discord.js'; import { createLogger } from '../core/logger.js'; import { startPollScheduler } from '../services/polls/poll-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'); @@ -11,6 +15,11 @@ export const once = true; export async function execute(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); startVoiceJanitor(client); startBotStatusRotation(client); diff --git a/src/events/guild-member-add.js b/src/events/guild-member-add.js index 8b0b8e2..067ba92 100644 --- a/src/events/guild-member-add.js +++ b/src/events/guild-member-add.js @@ -1,4 +1,5 @@ import { Events } from 'discord.js'; +import { readSetting } from '../config/guild-settings.js'; import { createLogger } from '../core/logger.js'; import { assignMemberRole, @@ -16,5 +17,5 @@ export async function execute(client, member) { await assignMemberRole(member); await sendWelcome(client, member); - await sendWelcomeDirectMessage(member); + if (readSetting('welcome.directMessage', member.guild.id)) await sendWelcomeDirectMessage(member); } diff --git a/src/index.js b/src/index.js index 548fbf2..0891893 100644 --- a/src/index.js +++ b/src/index.js @@ -4,9 +4,15 @@ import { loadCommands } from './core/command-loader.js'; import { registerEvents } from './core/event-loader.js'; import { logger } from './core/logger.js'; import { closeDatabase, initDatabase } from './database/index.js'; +import { startWebServer, webhookSharesWebPort } from './web/server.js'; import { startWebhookServer } from './webhooks/server.js'; -assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); +try { + assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); +} catch (error) { + logger.error(`${error.message}. Lance \`npm run setup\` pour remplir le .env pas à pas.`); + throw error; +} initDatabase(); @@ -17,7 +23,18 @@ for (const command of await loadCommands()) { } await registerEvents(client); -const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null; +// When both listen on the same port, the dashboard serves the webhook route too. +const webServer = env.web.enabled ? startWebServer({ 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('uncaughtException', (error) => logger.error('Uncaught exception', error)); @@ -25,6 +42,7 @@ process.on('uncaughtException', (error) => logger.error('Uncaught exception', er async function shutdown(signal) { logger.info(`Received ${signal}, shutting down`); webhookServer?.close(); + webServer?.close(); await client.destroy(); closeDatabase(); process.exit(0); diff --git a/src/services/gitea/gitea-admin.js b/src/services/gitea/gitea-admin.js new file mode 100644 index 0000000..841099a --- /dev/null +++ b/src/services/gitea/gitea-admin.js @@ -0,0 +1,153 @@ +import { env } from '../../config/env.js'; +import { asList, giteaRequest } from './gitea-client.js'; + +/** + * Administration endpoints used by the web dashboard (M16-T04). + * + * `gitea-client.js` stays focused on the single repository the Discord commands + * talk to; this module addresses any repository of the organization, which is + * what the dashboard needs. + */ + +const query = (params = {}) => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null && value !== '') search.set(key, String(value)); + } + const rendered = search.toString(); + return rendered ? `?${rendered}` : ''; +}; + +const path = (owner, repo) => `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`; + +/** Organization the dashboard manages by default. */ +export const defaultOwner = () => env.gitea.owner; + +export const org = { + get: (owner = defaultOwner()) => giteaRequest(`/orgs/${encodeURIComponent(owner)}`), + update: (payload, owner = defaultOwner()) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}`, { method: 'PATCH', body: payload }), + listRepos: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos${query({ page, limit })}`).then(asList), + listMembers: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/members${query({ page, limit })}`).then(asList), + listTeams: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/teams${query({ page, limit })}`).then(asList), + listTeamMembers: (teamId) => giteaRequest(`/teams/${teamId}/members`).then(asList), + listLabels: ({ owner = defaultOwner(), limit = 100 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/labels${query({ limit })}`).then(asList), + listHooks: ({ owner = defaultOwner() } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList), + createRepo: (payload, owner = defaultOwner()) => + 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. */ + whoami: () => giteaRequest('/user'), +}; + +export const repos = { + get: (owner, repo) => giteaRequest(path(owner, repo)), + update: (owner, repo, payload) => giteaRequest(path(owner, repo), { method: 'PATCH', body: payload }), + remove: (owner, repo) => giteaRequest(path(owner, repo), { method: 'DELETE' }), + + listBranches: (owner, repo, { page = 1, limit = 50 } = {}) => + giteaRequest(`${path(owner, repo)}/branches${query({ page, limit })}`).then(asList), + createBranch: (owner, repo, { newBranchName, oldBranchName }) => + giteaRequest(`${path(owner, repo)}/branches`, { + method: 'POST', + body: { new_branch_name: newBranchName, old_branch_name: oldBranchName }, + }), + removeBranch: (owner, repo, branch) => + giteaRequest(`${path(owner, repo)}/branches/${encodeURIComponent(branch)}`, { method: 'DELETE' }), + listTags: (owner, repo, { limit = 50 } = {}) => + giteaRequest(`${path(owner, repo)}/tags${query({ limit })}`).then(asList), + listCommits: (owner, repo, { sha, page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/commits${query({ sha, page, limit })}`).then(asList), + languages: (owner, repo) => giteaRequest(`${path(owner, repo)}/languages`), + listTopics: (owner, repo) => giteaRequest(`${path(owner, repo)}/topics`), + replaceTopics: (owner, repo, topics) => + giteaRequest(`${path(owner, repo)}/topics`, { method: 'PUT', body: { topics } }), + + listIssues: (owner, repo, { state = 'open', type = 'issues', page = 1, limit = 20, q } = {}) => + giteaRequest(`${path(owner, repo)}/issues${query({ state, type, page, limit, q })}`).then(asList), + createIssue: (owner, repo, { title, body, labels, assignees }) => + giteaRequest(`${path(owner, repo)}/issues`, { method: 'POST', body: { title, body, labels, assignees } }), + updateIssue: (owner, repo, number, payload) => + giteaRequest(`${path(owner, repo)}/issues/${number}`, { method: 'PATCH', body: payload }), + commentIssue: (owner, repo, number, body) => + giteaRequest(`${path(owner, repo)}/issues/${number}/comments`, { method: 'POST', body: { body } }), + listLabels: (owner, repo, { limit = 100 } = {}) => + giteaRequest(`${path(owner, repo)}/labels${query({ limit })}`).then(asList), + + listPulls: (owner, repo, { state = 'open', page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/pulls${query({ state, page, limit })}`).then(asList), + createPull: (owner, repo, { title, body, head, base }) => + giteaRequest(`${path(owner, repo)}/pulls`, { method: 'POST', body: { title, body, head, base } }), + mergePull: (owner, repo, number, { style = 'squash', title, message, deleteBranch = false } = {}) => + giteaRequest(`${path(owner, repo)}/pulls/${number}/merge`, { + method: 'POST', + body: { + Do: style, + MergeTitleField: title, + MergeMessageField: message, + delete_branch_after_merge: deleteBranch, + }, + }), + + listReleases: (owner, repo, { page = 1, limit = 20, draft, preRelease } = {}) => + giteaRequest( + `${path(owner, repo)}/releases${query({ page, limit, draft, 'pre-release': preRelease })}`, + ).then(asList), + getRelease: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/releases/${id}`), + latestRelease: (owner, repo) => giteaRequest(`${path(owner, repo)}/releases/latest`), + createRelease: (owner, repo, { tagName, target, name, body, draft = false, prerelease = false }) => + giteaRequest(`${path(owner, repo)}/releases`, { + method: 'POST', + body: { tag_name: tagName, target_commitish: target, name, body, draft, prerelease }, + }), + updateRelease: (owner, repo, id, payload) => + giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'PATCH', body: payload }), + removeRelease: (owner, repo, id) => + giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'DELETE' }), + + listCollaborators: (owner, repo) => giteaRequest(`${path(owner, repo)}/collaborators`).then(asList), + addCollaborator: (owner, repo, username, permission = 'write') => + giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { + method: 'PUT', + body: { permission }, + }), + removeCollaborator: (owner, repo, username) => + giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { method: 'DELETE' }), + + listHooks: (owner, repo) => giteaRequest(`${path(owner, repo)}/hooks`).then(asList), + createHook: (owner, repo, { url, secret, events, type = 'gitea' }) => + giteaRequest(`${path(owner, repo)}/hooks`, { + method: 'POST', + body: { type, active: true, events, config: { url, content_type: 'json', secret } }, + }), + removeHook: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/hooks/${id}`, { method: 'DELETE' }), + + /** Gitea Actions. Absent before Gitea 1.20, so callers must tolerate a 404. */ + listActionTasks: (owner, repo, { page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/actions/tasks${query({ page, limit })}`), + dispatchWorkflow: (owner, repo, workflow, { ref, inputs = {} }) => + giteaRequest(`${path(owner, repo)}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, { + method: 'POST', + body: { ref, inputs }, + }), +}; + +/** Splits `FWS/FWS-Arch` into its two parts, rejecting anything else. */ +export function splitRepository(fullName) { + const [owner, repo, ...rest] = String(fullName ?? '').split('/'); + if (!owner || !repo || rest.length > 0) return null; + return { owner, repo }; +} diff --git a/src/services/members/member-service.js b/src/services/members/member-service.js index 6f20982..0f907fc 100644 --- a/src/services/members/member-service.js +++ b/src/services/members/member-service.js @@ -1,5 +1,6 @@ import { COLORS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { createLogger } from '../../core/logger.js'; import { logEvent } from '../../database/repositories/event-log-repository.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). */ 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) { log.debug('No welcome channel configured'); return; @@ -25,13 +30,17 @@ export async function sendWelcome(client, member) { return; } + const greeting = + readSetting('welcome.message', member.guild.id).replaceAll('{server}', member.guild.name) || + DEFAULT_WELCOME; + const embed = baseEmbed(COLORS.primary) .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 }) .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}>` }); } @@ -41,6 +50,8 @@ export async function sendWelcome(client, member) { /** Gives the default member role (M7-T03). */ export async function assignMemberRole(member) { + if (!readSetting('members.autoRole', member.guild.id)) return; + const roleId = env.roles.member; 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). */ export async function announceDeparture(client, member) { + if (!readSetting('departure.announce', member.guild.id)) return; + const channelId = env.channels.logs || env.channels.modLogs; if (!channelId) return; diff --git a/src/services/moderation/moderation-service.js b/src/services/moderation/moderation-service.js index b0562f8..2afeae0 100644 --- a/src/services/moderation/moderation-service.js +++ b/src/services/moderation/moderation-service.js @@ -1,5 +1,6 @@ import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { UserFacingError } from '../../core/errors.js'; import { canActOn } from '../../core/permissions.js'; import { logEvent } from '../../database/repositories/event-log-repository.js'; @@ -95,6 +96,19 @@ export async function sendModerationLog( await channel.send({ embeds: [embed] }).catch(() => {}); } +/** + * Sends the private notice to the sanctioned member, when the server wants one + * (M8-T07). Never throws: plenty of accounts refuse direct messages, and that + * must not turn a successful sanction into an error. + */ +export async function notifyTarget(member, payload) { + if (!readSetting('moderation.dmTarget', member.guild.id)) return false; + return member + .send(payload) + .then(() => true) + .catch(() => false); +} + /** Direct message sent to the member who is being moderated (M8-T07). */ export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { const meta = MODERATION_ACTIONS[action]; diff --git a/src/services/notifications/notification-service.js b/src/services/notifications/notification-service.js index 999824a..8d9a6fd 100644 --- a/src/services/notifications/notification-service.js +++ b/src/services/notifications/notification-service.js @@ -1,4 +1,5 @@ import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { createLogger } from '../../core/logger.js'; import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; import { errorEmbed } from '../../ui/embeds.js'; @@ -16,17 +17,33 @@ const defaultChannels = { community: env.channels.logs, }; +/** + * `/notify` and the dashboard name the types after `NOTIFICATION_TYPES`, while the + * webhook handler names them after the Gitea event. Both spellings must resolve to + * the same channel, otherwise an override set from Discord is never applied (M9-T01). + */ +const TYPE_ALIASES = Object.freeze({ + pull_request: 'pull_requests', + pull_requests: 'pull_request', + push: 'commits', + commits: 'push', + release: 'releases', + releases: 'release', +}); + /** SQLite override first, then the environment default (M9-T01). */ export function resolveChannelId(type, guildId = env.discord.guildId) { try { if (guildId) { - const override = getNotificationChannel(guildId, type); - if (override?.channel_id) return override.channel_id; + for (const candidate of [type, TYPE_ALIASES[type]].filter(Boolean)) { + const override = getNotificationChannel(guildId, candidate); + if (override?.channel_id) return override.channel_id; + } } } catch { // The database is unavailable (tests, early startup): use the environment. } - return defaultChannels[type] ?? null; + return defaultChannels[type] ?? defaultChannels[TYPE_ALIASES[type]] ?? null; } /** Sends a notification payload to the channel configured for its type (M9). */ @@ -42,7 +59,15 @@ export async function notify(client, type, payload) { log.warn(`Notification channel unavailable for ${type}`, { channelId }); 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). */ diff --git a/src/services/tickets/ticket-service.js b/src/services/tickets/ticket-service.js index 4666d8c..ecd2890 100644 --- a/src/services/tickets/ticket-service.js +++ b/src/services/tickets/ticket-service.js @@ -1,5 +1,6 @@ import { ChannelType, PermissionFlagsBits } from 'discord.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 { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.js'; @@ -235,10 +236,13 @@ export async function closeTicket(interaction, reason = null) { payload: { ticketId: ticket.id, reason }, }); + const deleteChannel = readSetting('tickets.deleteChannelOnClose', ticket.guild_id); await interaction.reply({ embeds: [ 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; - 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). */ diff --git a/src/services/voice/voice-service.js b/src/services/voice/voice-service.js index 344a892..97a03e8 100644 --- a/src/services/voice/voice-service.js +++ b/src/services/voice/voice-service.js @@ -9,6 +9,7 @@ import { } from 'discord.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.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 * 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) { for (const guild of client.guilds.cache.values()) { let rows = []; diff --git a/src/web/api/community.js b/src/web/api/community.js new file mode 100644 index 0000000..4680904 --- /dev/null +++ b/src/web/api/community.js @@ -0,0 +1,224 @@ +import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { countVotes, listPolls } from '../../database/repositories/poll-repository.js'; +import { closeTicket, listTickets } from '../../database/repositories/ticket-repository.js'; +import { listVoiceChannels } from '../../database/repositories/voice-repository.js'; +import { listBotStatuses } from '../../database/repositories/bot-status-repository.js'; +import { closePollById } from '../../services/polls/poll-service.js'; +import { + addBotStatus, + applyStatusIfAlone, + clampRotation, + getRotationSeconds, + removeBotStatus, + saveRotationSeconds, + toggleBotStatus, +} from '../../services/status/bot-status-service.js'; +import { + deleteVoiceChannel, + listTriggerSummaries, + removeVoiceTriggerConfig, + saveVoiceTrigger, + setTriggerEnabled, +} from '../../services/voice/voice-service.js'; +import { badRequest, notFound } from '../http.js'; + +/** Tickets, polls, temporary voice channels and bot presence (M16-T05). */ + +const guildId = () => env.discord.guildId; + +export function registerCommunityRoutes(router) { + // --- Tickets --------------------------------------------------------------- + router.get( + '/api/community/tickets', + ({ query }) => ({ + categories: TICKET_CATEGORIES, + tickets: listTickets({ + guildId: guildId(), + status: query.get('status'), + authorId: query.get('authorId'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200), + }), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/tickets/:id/close', + async ({ params, body, actor, context }) => { + const id = Number.parseInt(params.id, 10); + const reason = String(body.reason ?? '').trim() || 'Clôturé depuis le tableau de bord'; + + const changes = closeTicket(id, { closedBy: actor.userId, reason }); + if (changes === 0) throw notFound('Ticket introuvable ou déjà clôturé.'); + + const ticket = listTickets({ guildId: guildId(), limit: 200 }).find((row) => row.id === id); + if (ticket?.channel_id && context.client) { + const channel = await context.client.channels.fetch(ticket.channel_id).catch(() => null); + await channel?.delete(`Ticket #${id} clôturé depuis le tableau de bord`).catch(() => null); + } + + logEvent({ guildId: guildId(), type: 'ticket.close', actorId: actor.userId, payload: { id, reason } }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Polls ----------------------------------------------------------------- + router.get( + '/api/community/polls', + ({ query }) => ({ + polls: listPolls({ + guildId: guildId(), + status: query.get('status'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100), + }).map((poll) => ({ + ...poll, + choices: JSON.parse(poll.choices), + counts: countVotes(poll.id), + })), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/polls/:id/close', + async ({ params, actor, context }) => { + // `closePollById` raises a `UserFacingError` when the poll is gone or already closed. + const id = Number.parseInt(params.id, 10); + await closePollById(context.client, id); + + logEvent({ guildId: guildId(), type: 'poll.close', actorId: actor.userId, payload: { id } }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Temporary voice channels --------------------------------------------- + router.get( + '/api/community/voice', + ({ context }) => { + const guild = context.client?.guilds?.cache?.get(guildId()); + return { + triggers: listTriggerSummaries(guildId()), + channels: listVoiceChannels(guildId()).map((row) => { + const channel = guild?.channels?.cache?.get(row.channel_id); + return { + ...row, + locked: Boolean(row.locked), + alive: Boolean(channel), + members: channel?.members?.size ?? 0, + }; + }), + defaults: { + triggerId: env.channels.voiceTrigger, + categoryId: env.channels.voiceCategory, + emptyGraceMs: env.voice.emptyGraceMs, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/community/voice/triggers/:triggerId', + ({ params, body, actor }) => { + if (!/^\d{17,20}$/.test(params.triggerId)) throw badRequest('Identifiant de salon invalide.'); + + const trigger = saveVoiceTrigger( + guildId(), + { + triggerId: params.triggerId, + label: body.label === undefined ? undefined : String(body.label), + categoryId: body.categoryId === undefined ? undefined : String(body.categoryId), + template: body.template === undefined ? undefined : String(body.template), + userLimit: body.userLimit === undefined ? undefined : Number.parseInt(body.userLimit, 10), + }, + actor.userId, + ); + return { trigger }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/community/voice/triggers/:triggerId/toggle', + ({ params, body }) => ({ + trigger: setTriggerEnabled(guildId(), params.triggerId, Boolean(body.enabled)), + }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/voice/triggers/:triggerId', + ({ params }) => { + removeVoiceTriggerConfig(guildId(), params.triggerId); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/voice/channels/:channelId', + async ({ params, context, actor }) => { + const channel = await context.client?.channels?.fetch(params.channelId).catch(() => null); + if (!channel) throw notFound('Salon introuvable.'); + + await deleteVoiceChannel(channel, `Supprimé depuis le tableau de bord par ${actor.username}`); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Bot presence ---------------------------------------------------------- + router.get( + '/api/community/statuses', + () => ({ + statuses: listBotStatuses(), + intervalSeconds: getRotationSeconds(guildId()), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/statuses', + ({ body, actor, context }) => { + const status = addBotStatus({ + text: String(body.text ?? ''), + type: String(body.type ?? 'watching'), + url: body.url ? String(body.url) : null, + createdBy: actor.userId, + }); + // Applies straight away when it is the only status, like `/status add` does. + if (context.client) applyStatusIfAlone(context.client); + return { status }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/community/statuses/:id', + // The service raises a `UserFacingError` for an unknown id or a no-op toggle. + ({ params, body }) => ({ + status: toggleBotStatus(Number.parseInt(params.id, 10), Boolean(body.enabled)), + }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/statuses/:id', + ({ params }) => ({ removed: removeBotStatus(Number.parseInt(params.id, 10)) }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.put( + '/api/community/statuses/interval', + ({ body, actor }) => { + const seconds = clampRotation(Number.parseInt(body.seconds ?? 0, 10), { strict: true }); + saveRotationSeconds(seconds, guildId(), actor.userId); + return { intervalSeconds: seconds, restartRequired: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/configuration.js b/src/web/api/configuration.js new file mode 100644 index 0000000..45139cc --- /dev/null +++ b/src/web/api/configuration.js @@ -0,0 +1,224 @@ +import { randomBytes } from 'node:crypto'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { badRequest, notFound } from '../http.js'; +import { + diffValues, + maskValues, + mergeValues, + readEnvFile, + renderEnvFile, + secretStatus, + writeEnvFile, +} from '../services/env-file.js'; +import { SECTIONS, VARIABLES, crossCheck, requiredKeys, validateAll } from '../services/env-schema.js'; + +/** + * Step by step `.env` wizard (M16-T09). + * + * Reachable by a bootstrap session, because its whole purpose is to run before + * the bot has a working configuration. + */ + +const log = createLogger('web:configuration'); +const WIZARD = { access: ACCESS_LEVELS.OWNER, setup: true }; + +/** Values currently loaded in the process, used to prefill a first run. */ +const runningValues = () => ({ + NODE_ENV: env.nodeEnv, + LOG_LEVEL: env.logLevel, + LOG_DIR: env.logDir, + LOG_RETENTION_DAYS: String(env.logRetentionDays), + DISCORD_CLIENT_ID: env.discord.clientId, + DISCORD_GUILD_ID: env.discord.guildId, + GITEA_URL: env.gitea.url, + GITEA_OWNER: env.gitea.owner, + GITEA_REPO: env.gitea.repo, + DATABASE_PATH: env.database.path, +}); + +function currentValues() { + const file = readEnvFile(); + const defaults = Object.fromEntries( + VARIABLES.filter((variable) => variable.default !== undefined).map((v) => [v.key, v.default]), + ); + return { file, values: { ...defaults, ...runningValues(), ...file.values } }; +} + +function report(values) { + const errors = validateAll(values); + const missing = requiredKeys().filter((key) => !String(values[key] ?? '').trim()); + return { + errors, + warnings: crossCheck(values), + missingRequired: missing, + valid: Object.keys(errors).length === 0, + }; +} + +export function registerConfigurationRoutes(router) { + router.get( + '/api/configuration', + () => { + const { file, values } = currentValues(); + return { + sections: SECTIONS, + variables: VARIABLES, + exists: file.exists, + unknownKeys: Object.keys(file.unknown), + values: maskValues(values), + secrets: secretStatus(values), + ...report(values), + }; + }, + WIZARD, + ); + + /** Live feedback while the form is being filled, nothing is written. */ + router.post( + '/api/configuration/validate', + ({ body }) => { + const { values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + return { ...report(next), diff: diffValues(values, next) }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/preview', + ({ body }) => { + const { file, values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + // Secrets are blanked out: the preview may be copied or screenshotted. + const safe = { ...next }; + for (const variable of VARIABLES) { + if (variable.type === 'secret' && safe[variable.key]) safe[variable.key] = '••••••••'; + } + return { content: renderEnvFile(safe, file.unknown) }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/save', + ({ body, actor }) => { + const { file, values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + const status = report(next); + + // A partial save is allowed while the wizard is still being walked through, + // but a malformed value never reaches the file. + if (!status.valid && body.force !== true) { + throw badRequest('Certaines valeurs sont invalides.', status.errors); + } + + const diff = diffValues(values, next); + if (diff.length === 0) return { ...status, diff, written: false }; + + const { backup } = writeEnvFile(next, { unknown: file.unknown }); + log.info('Configuration saved from the wizard', { + actor: actor.userId ?? 'setup', + changed: diff.map((entry) => entry.key), + }); + + return { + ...status, + diff, + written: true, + backup, + restartRequired: diff.some((entry) => entry.restartRequired), + }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/generate', + ({ body }) => { + const kind = String(body.kind ?? 'hex32'); + const sizes = { hex16: 16, hex32: 32 }; + if (!(kind in sizes)) throw badRequest('Type de secret inconnu.'); + return { value: randomBytes(sizes[kind]).toString('hex') }; + }, + WIZARD, + ); + + /** + * Tries the credentials the user just typed, before they are written to disk. + * Nothing is stored and the value never appears in the response. + */ + router.post( + '/api/configuration/test/:service', + async ({ params, body }) => { + const values = mergeValues(currentValues().values, body.values ?? {}); + + if (params.service === 'discord') { + const token = String(values.DISCORD_TOKEN ?? ''); + if (!token) return { ok: false, detail: 'Aucun token à tester.' }; + + try { + const response = await fetch('https://discord.com/api/v10/users/@me', { + headers: { Authorization: `Bot ${token}` }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { + return { + ok: false, + detail: + response.status === 401 + ? 'Token refusé par Discord. Vérifie que tu as bien copié le token du bot (et non le client secret).' + : `Discord a répondu ${response.status}.`, + }; + } + const user = await response.json(); + return { + ok: true, + detail: `Token valide : ${user.username} (${user.id}).`, + applicationId: user.id, + }; + } catch (error) { + return { ok: false, detail: `Discord injoignable : ${error.message}` }; + } + } + + if (params.service === 'gitea') { + const url = String(values.GITEA_URL ?? '').replace(/\/+$/, ''); + const token = String(values.GITEA_TOKEN ?? ''); + if (!url || !token) return { ok: false, detail: 'URL ou jeton manquant.' }; + + try { + const response = await fetch(`${url}/api/v1/user`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) return { ok: false, detail: `Gitea a répondu ${response.status}.` }; + + const user = await response.json(); + const owner = String(values.GITEA_OWNER ?? ''); + let detail = `Jeton valide pour « ${user.login} ».`; + let organizationReachable = true; + + if (owner) { + const orgResponse = await fetch(`${url}/api/v1/orgs/${encodeURIComponent(owner)}`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + organizationReachable = orgResponse.ok; + detail += orgResponse.ok + ? ` Organisation « ${owner} » accessible.` + : ` En revanche l’organisation « ${owner} » est inaccessible (${orgResponse.status}).`; + } + // The token itself works: an unreachable organization is a warning, not a failure. + return { ok: true, warning: !organizationReachable, detail }; + } catch (error) { + return { ok: false, detail: `Gitea injoignable : ${error.message}` }; + } + } + + throw notFound('Service inconnu.'); + }, + WIZARD, + ); +} diff --git a/src/web/api/deployments.js b/src/web/api/deployments.js new file mode 100644 index 0000000..719d940 --- /dev/null +++ b/src/web/api/deployments.js @@ -0,0 +1,254 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { + createTarget, + getDeployment, + getTarget, + listDeployments, + listTargets, + removeTarget, + updateTarget, +} from '../../database/repositories/deploy-repository.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { splitRepository } from '../../services/gitea/gitea-admin.js'; +import { badRequest, forbidden, notFound } from '../http.js'; +import { assertRunnable, describeTarget, runDeployment } from '../services/deploy-service.js'; + +/** Deploy targets and deployment history (M16-T06 / M16-T07). */ + +const KINDS = ['webhook', 'command', 'gitea-action']; +const guildId = () => env.discord.guildId; + +/** A target's config may hold a shared secret, which never leaves the server. */ +const publicTarget = (target) => ({ + id: target.id, + name: target.name, + repository: target.repository, + environment: target.environment, + kind: target.kind, + autoDeploy: target.auto_deploy, + enabled: target.enabled, + summary: describeTarget(target), + config: { + url: target.config.url ?? null, + method: target.config.method ?? null, + command: target.config.command ?? null, + cwd: target.config.cwd ?? null, + workflow: target.config.workflow ?? null, + ref: target.config.ref ?? null, + hasSecret: Boolean(target.config.secret), + }, + createdBy: target.created_by, + createdAt: target.created_at, + updatedAt: target.updated_at, +}); + +function readTargetPayload(body, { partial = false } = {}) { + const config = {}; + const payload = {}; + + const kind = body.kind === undefined && partial ? undefined : String(body.kind ?? ''); + if (kind !== undefined) { + if (!KINDS.includes(kind)) throw badRequest(`Type de cible attendu : ${KINDS.join(', ')}.`); + payload.kind = kind; + } + + if (body.name !== undefined) { + const name = String(body.name).trim(); + if (!/^[\w .-]{2,60}$/.test(name)) throw badRequest('Nom de cible invalide (2 à 60 caractères).'); + payload.name = name; + } + + if (body.repository !== undefined) { + const repository = String(body.repository).trim(); + if (!splitRepository(repository)) throw badRequest('Dépôt attendu au format `organisation/depot`.'); + payload.repository = repository; + } + + if (body.environment !== undefined) { + const environment = String(body.environment).trim(); + if (!/^[\w-]{2,30}$/.test(environment)) throw badRequest('Nom d’environnement invalide.'); + payload.environment = environment; + } + + if (body.autoDeploy !== undefined) payload.auto_deploy = Boolean(body.autoDeploy); + if (body.enabled !== undefined) payload.enabled = Boolean(body.enabled); + + if (body.config && typeof body.config === 'object') { + const source = body.config; + if (source.url !== undefined) { + const url = String(source.url).trim(); + if (url && !/^https?:\/\//.test(url)) throw badRequest('L’URL du webhook doit être en http(s).'); + config.url = url; + } + if (source.method !== undefined) { + const method = String(source.method).toUpperCase(); + if (!['POST', 'PUT', 'PATCH'].includes(method)) throw badRequest('Méthode HTTP non autorisée.'); + config.method = method; + } + if (source.secret !== undefined) config.secret = String(source.secret); + if (source.headers !== undefined && typeof source.headers === 'object') config.headers = source.headers; + if (source.command !== undefined) config.command = String(source.command); + if (source.cwd !== undefined) config.cwd = String(source.cwd); + if (source.workflow !== undefined) config.workflow = String(source.workflow); + if (source.ref !== undefined) config.ref = String(source.ref); + if (source.inputs !== undefined && typeof source.inputs === 'object') config.inputs = source.inputs; + payload.config = config; + } + + return payload; +} + +/** Command targets execute shell on the host, so they stay Owner-only. */ +function assertMayManage(actor, kind) { + if (kind !== 'command') return; + if (!env.web.allowCommandDeploys) { + throw forbidden('Les cibles de type commande sont désactivées (`WEB_ALLOW_COMMAND_DEPLOYS`).'); + } + if (actor.accessLevel < ACCESS_LEVELS.OWNER) { + throw forbidden('Seul le niveau Owner peut gérer une cible de type commande.'); + } +} + +export function registerDeploymentRoutes(router) { + router.get( + '/api/deploy/targets', + ({ query }) => ({ + targets: listTargets({ guildId: guildId(), repository: query.get('repository') }).map(publicTarget), + commandDeploysAllowed: env.web.allowCommandDeploys, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/deploy/targets', + ({ body, actor }) => { + const payload = readTargetPayload(body); + if (!payload.name || !payload.repository || !payload.kind) { + throw badRequest('`name`, `repository` et `kind` sont obligatoires.'); + } + assertMayManage(actor, payload.kind); + + const target = createTarget({ + guildId: guildId(), + name: payload.name, + repository: payload.repository, + environment: payload.environment ?? 'production', + kind: payload.kind, + config: payload.config ?? {}, + autoDeploy: payload.auto_deploy ?? false, + enabled: payload.enabled ?? true, + createdBy: actor.userId, + }); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.create', + actorId: actor.userId, + payload: { name: target.name, kind: target.kind }, + }); + return publicTarget(target); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/deploy/targets/:id', + ({ params, body, actor }) => { + const current = getTarget(Number.parseInt(params.id, 10)); + if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + const payload = readTargetPayload(body, { partial: true }); + assertMayManage(actor, payload.kind ?? current.kind); + + // A partial config patch must not wipe the secret already stored. + if (payload.config) payload.config = { ...current.config, ...payload.config }; + + const updated = updateTarget(current.id, payload); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.update', + actorId: actor.userId, + payload: { name: updated.name }, + }); + return publicTarget(updated); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/deploy/targets/:id', + ({ params, actor }) => { + const current = getTarget(Number.parseInt(params.id, 10)); + if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + removeTarget(current.id); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.delete', + actorId: actor.userId, + payload: { name: current.name }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + /** Dry run: checks the target without contacting anything. */ + router.post( + '/api/deploy/targets/:id/check', + ({ params }) => { + const target = getTarget(Number.parseInt(params.id, 10)); + if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + try { + assertRunnable(target); + return { ok: true, summary: describeTarget(target) }; + } catch (error) { + return { ok: false, reason: error.message }; + } + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/deploy/targets/:id/run', + async ({ params, body, actor, context }) => { + const target = getTarget(Number.parseInt(params.id, 10)); + if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.'); + assertMayManage(actor, target.kind); + + const deployment = await runDeployment(context.client, target, { + ref: body.ref ? String(body.ref) : null, + releaseTag: body.releaseTag ? String(body.releaseTag) : null, + source: 'web', + triggeredBy: actor.userId, + }); + return deployment; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.get( + '/api/deployments', + ({ query }) => ({ + deployments: listDeployments({ + guildId: guildId(), + repository: query.get('repository'), + status: query.get('status'), + targetId: query.get('targetId') ? Number.parseInt(query.get('targetId'), 10) : null, + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100), + }), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/deployments/:id', + ({ params }) => { + const deployment = getDeployment(Number.parseInt(params.id, 10)); + if (!deployment || deployment.guild_id !== guildId()) throw notFound('Déploiement introuvable.'); + return deployment; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/discord.js b/src/web/api/discord.js new file mode 100644 index 0000000..07e3add --- /dev/null +++ b/src/web/api/discord.js @@ -0,0 +1,404 @@ +import { ChannelType, REST, Routes } from 'discord.js'; +import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { ExternalApiError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { canActOn, getAccessLevel } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + countByAction, + listActions, + recordAction, +} from '../../database/repositories/moderation-repository.js'; +import { + listNotificationChannels, + removeNotificationChannel, + setNotificationChannel, +} from '../../database/repositories/notification-repository.js'; +import { sendModerationLog } from '../../services/moderation/moderation-service.js'; +import { badRequest, forbidden, notFound } from '../http.js'; + +/** Discord server management from the dashboard (M16-T05). */ + +const log = createLogger('web:discord'); +const guildId = () => env.discord.guildId; + +function guildOf(context) { + const guild = context.client?.guilds?.cache?.get(guildId()); + if (!guild) throw badRequest('Le bot n’est connecté à aucun serveur pour l’instant.'); + return guild; +} + +/** Resolves the caller as a guild member so the role hierarchy can be enforced. */ +async function actingMember(guild, actor) { + if (!actor.userId) throw forbidden('Cette action demande une session Discord, pas un jeton d’API.'); + const member = await guild.members.fetch(actor.userId).catch(() => null); + if (!member) throw forbidden('Ton compte n’est plus membre du serveur.'); + return member; +} + +const CHANNEL_KINDS = { + [ChannelType.GuildText]: 'text', + [ChannelType.GuildVoice]: 'voice', + [ChannelType.GuildCategory]: 'category', + [ChannelType.GuildAnnouncement]: 'announcement', + [ChannelType.GuildStageVoice]: 'stage', + [ChannelType.GuildForum]: 'forum', +}; + +const summarizeMember = (member) => ({ + id: member.id, + username: member.user.username, + displayName: member.displayName, + avatar: member.displayAvatarURL({ size: 64 }), + bot: member.user.bot, + joinedAt: member.joinedAt?.toISOString() ?? null, + createdAt: member.user.createdAt?.toISOString() ?? null, + roles: member.roles.cache.filter((role) => role.id !== member.guild.id).map((role) => role.id), + accessLevel: getAccessLevel(member), + accessLabel: ACCESS_LABELS[getAccessLevel(member)], + timeoutUntil: member.communicationDisabledUntil?.toISOString() ?? null, +}); + +export function registerDiscordRoutes(router) { + router.get( + '/api/discord/guild', + async ({ context }) => { + const guild = guildOf(context); + await guild.channels.fetch().catch(() => null); + + return { + id: guild.id, + name: guild.name, + description: guild.description, + icon: guild.iconURL({ size: 256 }), + banner: guild.bannerURL({ size: 512 }), + ownerId: guild.ownerId, + memberCount: guild.memberCount, + createdAt: guild.createdAt?.toISOString() ?? null, + boostTier: guild.premiumTier, + boostCount: guild.premiumSubscriptionCount, + verificationLevel: guild.verificationLevel, + features: guild.features, + channels: guild.channels.cache + .map((channel) => ({ + id: channel.id, + name: channel.name, + kind: CHANNEL_KINDS[channel.type] ?? 'other', + parentId: channel.parentId, + position: channel.rawPosition, + nsfw: channel.nsfw ?? false, + topic: channel.topic ?? null, + })) + .sort((a, b) => a.position - b.position), + roles: guild.roles.cache + .filter((role) => role.id !== guild.id) + .map((role) => ({ + id: role.id, + name: role.name, + color: role.hexColor, + position: role.position, + managed: role.managed, + mentionable: role.mentionable, + memberCount: role.members.size, + })) + .sort((a, b) => b.position - a.position), + mapping: { + roles: env.roles, + channels: env.channels, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/members', + async ({ context, query }) => { + const guild = guildOf(context); + const search = (query.get('q') ?? '').trim().toLowerCase(); + const limit = Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200); + + const members = await guild.members.fetch().catch(() => guild.members.cache); + const matched = members + .filter((member) => + search === '' + ? true + : member.user.username.toLowerCase().includes(search) || + member.displayName.toLowerCase().includes(search) || + member.id === search, + ) + .first(limit); + + return { total: guild.memberCount, members: matched.map(summarizeMember) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/members/:id', + async ({ context, params }) => { + const guild = guildOf(context); + const member = await guild.members.fetch(params.id).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + + return { + ...summarizeMember(member), + history: listActions({ guildId: guild.id, targetId: member.id, limit: 50 }), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/discord/members/:id/roles', + async ({ context, params, body, actor }) => { + const guild = guildOf(context); + const actorMember = await actingMember(guild, actor); + const member = await guild.members.fetch(params.id).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); + + const roleId = String(body.roleId ?? ''); + const role = guild.roles.cache.get(roleId); + if (!role) throw badRequest('Rôle introuvable.'); + if (role.position >= actorMember.roles.highest.position && guild.ownerId !== actorMember.id) { + throw forbidden('Ce rôle est au-dessus du tien.'); + } + + const action = body.action === 'remove' ? 'remove' : 'add'; + if (action === 'add') await member.roles.add(role, `Tableau de bord — ${actor.username}`); + else await member.roles.remove(role, `Tableau de bord — ${actor.username}`); + + recordAction({ + guildId: guild.id, + action: 'role', + moderatorId: actor.userId, + targetId: member.id, + reason: `${action === 'add' ? 'Ajout' : 'Retrait'} du rôle ${role.name} depuis le tableau de bord`, + }); + return { ok: true, roles: summarizeMember(member).roles }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Applies a moderation action, mirroring what the slash commands do (M8). */ + router.post( + '/api/discord/moderation', + async ({ context, body, actor }) => { + const guild = guildOf(context); + const actorMember = await actingMember(guild, actor); + + const action = String(body.action ?? ''); + if (!['warn', 'mute', 'kick', 'ban'].includes(action)) { + throw badRequest('Action attendue : warn, mute, kick ou ban.'); + } + + const member = await guild.members.fetch(String(body.userId ?? '')).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); + + const reason = String(body.reason ?? '').trim() || 'Non précisé'; + const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null; + if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) { + throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.'); + } + + const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`; + if (action === 'mute') await member.timeout(durationMs, audit); + else if (action === 'kick') await member.kick(audit); + else if (action === 'ban') await member.ban({ reason: audit, deleteMessageSeconds: 0 }); + + recordAction({ + guildId: guild.id, + action, + moderatorId: actor.userId, + targetId: member.id, + reason, + durationMs, + }); + logEvent({ + guildId: guild.id, + type: `moderation.${action}`, + actorId: actor.userId, + payload: { targetId: member.id, reason, durationMs, source: 'web' }, + }); + await sendModerationLog(context.client, guild, { + action, + targetId: member.id, + moderatorId: actor.userId, + reason, + durationMs, + }); + + return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/moderation', + ({ query }) => ({ + actions: listActions({ + guildId: guildId(), + targetId: query.get('userId'), + action: query.get('action'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200), + }), + totals: countByAction(guildId()), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + /** Publishes a message in a channel: announcements, maintenance notices. */ + router.post( + '/api/discord/announce', + async ({ context, body, actor }) => { + const guild = guildOf(context); + const channelId = String(body.channelId ?? '') || env.channels.announcements; + if (!channelId) throw badRequest('Aucun salon de destination.'); + + const channel = await context.client.channels.fetch(channelId).catch(() => null); + if (!channel?.isSendable()) throw badRequest('Salon introuvable ou non accessible en écriture.'); + + const content = String(body.content ?? '').trim(); + const title = String(body.title ?? '').trim(); + if (content === '' && title === '') throw badRequest('Le message est vide.'); + + const payload = body.asEmbed + ? { + embeds: [ + { + title: title || undefined, + description: content || undefined, + color: Number.parseInt(String(body.color ?? '0x1793d1'), 16) || 0x1793d1, + footer: { text: `Publié par ${actor.displayName ?? actor.username}` }, + timestamp: new Date().toISOString(), + }, + ], + } + : { content: title ? `**${title}**\n${content}` : content }; + + const message = await channel.send(payload); + logEvent({ + guildId: guild.id, + type: 'web.announce', + actorId: actor.userId, + payload: { channelId, messageId: message.id }, + }); + log.info('Announcement published from the dashboard', { channelId, actor: actor.userId }); + return { ok: true, messageId: message.id, url: message.url }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Notification routing -------------------------------------------------- + router.get( + '/api/discord/notifications', + () => ({ + overrides: listNotificationChannels(guildId()), + defaults: { + issues: env.channels.notifIssues, + pull_requests: env.channels.notifPullRequests, + commits: env.channels.notifCommits, + releases: env.channels.notifReleases, + errors: env.channels.notifErrors, + announcements: env.channels.announcements, + community: env.channels.logs, + }, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/discord/notifications/:type', + ({ params, body, actor }) => { + const channelId = String(body.channelId ?? '').trim(); + if (channelId === '') { + removeNotificationChannel(guildId(), params.type); + return { ok: true, removed: true }; + } + if (!/^\d{17,20}$/.test(channelId)) throw badRequest('Identifiant de salon invalide.'); + + setNotificationChannel({ + guildId: guildId(), + type: params.type, + channelId, + detailLevel: String(body.detailLevel ?? 'normal'), + }); + logEvent({ + guildId: guildId(), + type: 'web.notifications.update', + actorId: actor.userId, + payload: { type: params.type, channelId }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** + * 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. */ + router.get( + '/api/discord/commands', + ({ context }) => ({ + commands: [...(context.client?.commands?.values() ?? [])] + .map((command) => { + // `toJSON()` flattens the builder, whose option objects are builders too. + const definition = command.data.toJSON(); + return { + name: definition.name, + description: definition.description, + access: command.access ?? ACCESS_LEVELS.USER, + accessLabel: ACCESS_LABELS[command.access ?? ACCESS_LEVELS.USER], + subcommandAccess: command.subcommandAccess ?? null, + options: (definition.options ?? []).map((option) => ({ + name: option.name, + description: option.description, + type: option.type, + })), + }; + }) + .sort((a, b) => a.name.localeCompare(b.name)), + }), + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/index.js b/src/web/api/index.js new file mode 100644 index 0000000..00a6099 --- /dev/null +++ b/src/web/api/index.js @@ -0,0 +1,72 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { registerAuthRoutes } from '../auth/routes.js'; +import { openEventStream } from '../events.js'; +import { VERSION, buildAt } from '../services/build-info.js'; +import { registerCommunityRoutes } from './community.js'; +import { registerConfigurationRoutes } from './configuration.js'; +import { registerDeploymentRoutes } from './deployments.js'; +import { registerDiscordRoutes } from './discord.js'; +import { registerLogRoutes } from './logs.js'; +import { registerOrganizationRoutes } from './organization.js'; +import { registerOverviewRoutes } from './overview.js'; +import { registerProjectRoutes } from './projects.js'; +import { registerReleaseRoutes } from './releases.js'; +import { registerRepositoryRoutes } from './repositories.js'; +import { registerSearchRoutes } from './search.js'; +import { registerSettingsRoutes } from './settings.js'; +import { registerStatusRoutes } from './status.js'; +import { registerWikiRoutes } from './wiki.js'; + +/** + * Route registration order matters only for readability: the router matches on + * the full pattern, not on declaration order. + */ +export function registerApiRoutes(router, { setupOnly = false } = {}) { + // Liveness probe for a reverse proxy or an uptime monitor. Registered first so + // it answers even in bootstrap mode, when nothing else is mounted. + router.get( + '/api/health', + ({ context }) => ({ + status: context.client?.isReady?.() ? 'ok' : 'starting', + setupOnly: context.setupOnly, + uptimeMs: Date.now() - context.startedAt, + version: VERSION, + buildAt: buildAt(), + }), + { public: true }, + ); + + registerAuthRoutes(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). + router.get( + '/api/events', + ({ request, response, actor }) => { + openEventStream(request, response, actor); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // In bootstrap mode the bot is not connected and the database may be empty: + // only the wizard makes sense. + if (setupOnly) return router; + + registerOverviewRoutes(router); + registerOrganizationRoutes(router); + registerProjectRoutes(router); + registerRepositoryRoutes(router); + registerReleaseRoutes(router); + registerDeploymentRoutes(router); + registerDiscordRoutes(router); + registerCommunityRoutes(router); + registerSearchRoutes(router); + registerSettingsRoutes(router); + registerLogRoutes(router); + return router; +} diff --git a/src/web/api/logs.js b/src/web/api/logs.js new file mode 100644 index 0000000..83a89d6 --- /dev/null +++ b/src/web/api/logs.js @@ -0,0 +1,96 @@ +import { readFile, readdir, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { maskSecrets } from '../../core/logger.js'; +import { getDatabase } from '../../database/index.js'; +import { badRequest, notFound } from '../http.js'; + +/** Functional event log and technical log files (M16-T05). */ + +const LOG_FILE = /^\d{4}-\d{2}-\d{2}\.log$/; + +export function registerLogRoutes(router) { + router.get( + '/api/logs/events', + ({ query }) => { + const clauses = []; + const params = []; + + const type = query.get('type'); + if (type) { + clauses.push('type LIKE ?'); + params.push(`${type}%`); + } + const actorId = query.get('actorId'); + if (actorId) { + clauses.push('actor_id = ?'); + params.push(actorId); + } + const limit = Math.min(Number.parseInt(query.get('limit') ?? '100', 10), 500); + params.push(limit); + + const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : ''; + const events = getDatabase() + .prepare(`SELECT * FROM event_logs ${where} ORDER BY id DESC LIMIT ?`) + .all(...params) + .map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null })); + + return { + events, + types: getDatabase() + .prepare( + 'SELECT type, COUNT(*) AS count FROM event_logs GROUP BY type ORDER BY count DESC LIMIT 40', + ) + .all(), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/logs/files', + async () => { + const entries = await readdir(env.logDir).catch(() => []); + const files = []; + + for (const name of entries.filter((entry) => LOG_FILE.test(entry))) { + const info = await stat(path.join(env.logDir, name)).catch(() => null); + if (info) files.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() }); + } + return { directory: env.logDir, files: files.sort((a, b) => b.name.localeCompare(a.name)) }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.get( + '/api/logs/files/:name', + async ({ params, query }) => { + // The name pattern is the only thing standing between this route and the + // rest of the filesystem, so it is strict on purpose. + if (!LOG_FILE.test(params.name)) throw badRequest('Nom de fichier de log invalide.'); + + const content = await readFile(path.join(env.logDir, params.name), 'utf8').catch(() => null); + if (content === null) throw notFound('Fichier de log introuvable.'); + + const lines = Math.min(Number.parseInt(query.get('lines') ?? '300', 10), 2000); + const level = query.get('level'); + const parsed = content + .split('\n') + .filter(Boolean) + .map((line) => { + try { + return JSON.parse(line); + } catch { + return { level: 'info', message: line }; + } + }) + .filter((entry) => !level || entry.level === level); + + // `maskSecrets` already ran at write time; it runs again in case the file + // predates a secret rotation. + return { name: params.name, entries: JSON.parse(maskSecrets(JSON.stringify(parsed.slice(-lines)))) }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/organization.js b/src/web/api/organization.js new file mode 100644 index 0000000..e78a8b8 --- /dev/null +++ b/src/web/api/organization.js @@ -0,0 +1,179 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { org } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { badRequest } from '../http.js'; + +/** Organization-wide management (M16-T04). */ + +const requireGitea = () => { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); +}; + +const toMember = (member) => ({ + id: member.id, + login: member.login ?? member.username, + fullName: member.full_name, + email: member.email, + avatar: member.avatar_url, + isAdmin: member.is_admin, + lastLogin: member.last_login, + createdAt: member.created, +}); + +export function registerOrganizationRoutes(router) { + router.get( + '/api/organization', + async () => { + requireGitea(); + const [details, members, teams, repositories] = await Promise.all([ + org.get(), + org.listMembers({ limit: 100 }).catch(() => []), + org.listTeams({ limit: 100 }).catch(() => []), + org.listRepos({ limit: 100 }).catch(() => []), + ]); + + return { + name: details.username ?? details.name, + fullName: details.full_name, + description: details.description, + website: details.website, + location: details.location, + email: details.email, + avatar: details.avatar_url, + visibility: details.visibility, + url: `${env.gitea.url}/${details.username ?? details.name}`, + members: members.map(toMember), + teams: teams.map((team) => ({ + id: team.id, + name: team.name, + description: team.description, + permission: team.permission, + includesAllRepositories: team.includes_all_repositories, + canCreateOrgRepo: team.can_create_org_repo, + units: team.units, + })), + repositories: repositories.map((repository) => ({ + id: repository.id, + fullName: repository.full_name, + name: repository.name, + description: repository.description, + private: repository.private, + archived: repository.archived, + fork: repository.fork, + template: repository.template, + defaultBranch: repository.default_branch, + stars: repository.stars_count, + forks: repository.forks_count, + watchers: repository.watchers_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + releases: repository.release_counter, + sizeKb: repository.size, + language: repository.language, + updatedAt: repository.updated_at, + createdAt: repository.created_at, + htmlUrl: repository.html_url, + hasIssues: repository.has_issues, + hasPullRequests: repository.has_pull_requests, + hasActions: repository.has_actions, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/organization', + async ({ body, actor }) => { + requireGitea(); + const payload = {}; + for (const field of ['full_name', 'description', 'website', 'location', 'visibility']) { + if (field in body) payload[field] = String(body[field] ?? ''); + } + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + await org.update(payload); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.organization.update', + actorId: actor.userId, + payload: { fields: Object.keys(payload) }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/organization/teams/:id/members', + async ({ params }) => { + requireGitea(); + const members = await org.listTeamMembers(Number.parseInt(params.id, 10)); + return { members: members.map(toMember) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/organization/labels', + async () => { + requireGitea(); + return { labels: await org.listLabels() }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/organization/hooks', + async () => { + requireGitea(); + const hooks = await org.listHooks().catch(() => []); + return { + hooks: hooks.map((hook) => ({ + id: hook.id, + type: hook.type, + active: hook.active, + events: hook.events, + url: hook.config?.url, + createdAt: hook.created_at, + })), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Creates a repository inside the organization (M16-T04). */ + router.post( + '/api/organization/repositories', + async ({ body, actor }) => { + requireGitea(); + const name = String(body.name ?? '').trim(); + if (!/^[\w.-]{1,100}$/.test(name)) { + throw badRequest('Nom de dépôt invalide : lettres, chiffres, `.`, `-` et `_` uniquement.'); + } + + const created = await org.createRepo({ + name, + description: String(body.description ?? ''), + private: Boolean(body.private), + auto_init: body.autoInit !== false, + default_branch: String(body.defaultBranch ?? 'main'), + gitignores: body.gitignores ?? undefined, + license: body.license ?? undefined, + readme: body.readme ?? undefined, + issue_labels: body.issueLabels ?? undefined, + }); + + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.repository.create', + actorId: actor.userId, + payload: { repository: created.full_name }, + }); + return { fullName: created.full_name, htmlUrl: created.html_url }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/overview.js b/src/web/api/overview.js new file mode 100644 index 0000000..a079516 --- /dev/null +++ b/src/web/api/overview.js @@ -0,0 +1,158 @@ +import { version as discordJsVersion } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { getDatabase } from '../../database/index.js'; +import { + countByStatus, + lastDeploymentPerEnvironment, +} from '../../database/repositories/deploy-repository.js'; +import { countByAction } from '../../database/repositories/moderation-repository.js'; +import { countPolls } from '../../database/repositories/poll-repository.js'; +import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; +import { countVoiceChannels } from '../../database/repositories/voice-repository.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { org } from '../../services/gitea/gitea-admin.js'; + +/** Aggregated landing page of the dashboard (M16-T05). */ + +const guildId = () => env.discord.guildId; + +function botSnapshot(client, startedAt) { + const guild = client?.guilds?.cache?.get(guildId()) ?? null; + return { + online: Boolean(client?.isReady?.()), + username: client?.user?.username ?? null, + discriminator: client?.user?.discriminator ?? null, + avatar: client?.user?.displayAvatarURL?.({ size: 128 }) ?? null, + ping: client?.ws?.ping ?? null, + uptimeMs: Date.now() - startedAt, + nodeVersion: process.version, + discordJsVersion, + memoryMb: Math.round(process.memoryUsage().rss / 1024 / 1024), + commands: client?.commands?.size ?? 0, + guild: guild + ? { + id: guild.id, + name: guild.name, + icon: guild.iconURL?.({ size: 128 }) ?? null, + memberCount: guild.memberCount, + channelCount: guild.channels.cache.size, + roleCount: guild.roles.cache.size, + boostTier: guild.premiumTier, + createdAt: guild.createdAt?.toISOString() ?? null, + } + : null, + }; +} + +function databaseSnapshot() { + const database = getDatabase(); + const tables = database + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name") + .all() + .map((row) => row.name); + + const counts = Object.fromEntries( + tables.map((table) => [table, database.prepare(`SELECT COUNT(*) AS count FROM "${table}"`).get().count]), + ); + const pageCount = database.prepare('PRAGMA page_count').get(); + const pageSize = database.prepare('PRAGMA page_size').get(); + + return { + path: env.database.path, + tables: counts, + sizeBytes: (pageCount?.page_count ?? 0) * (pageSize?.page_size ?? 0), + migrations: database.prepare('SELECT name, applied_at FROM schema_migrations ORDER BY name').all(), + }; +} + +async function giteaSnapshot() { + if (!isGiteaConfigured()) return { configured: false }; + + const [organization, repositories] = await Promise.all([ + org.get().catch(() => null), + org.listRepos({ limit: 50 }).catch(() => []), + ]); + + const totals = repositories.reduce( + (accumulator, repository) => ({ + openIssues: accumulator.openIssues + (repository.open_issues_count ?? 0), + openPulls: accumulator.openPulls + (repository.open_pr_counter ?? 0), + stars: accumulator.stars + (repository.stars_count ?? 0), + forks: accumulator.forks + (repository.forks_count ?? 0), + sizeKb: accumulator.sizeKb + (repository.size ?? 0), + }), + { openIssues: 0, openPulls: 0, stars: 0, forks: 0, sizeKb: 0 }, + ); + + return { + configured: true, + url: env.gitea.url, + organization: organization && { + name: organization.username ?? organization.name, + fullName: organization.full_name, + description: organization.description, + website: organization.website, + location: organization.location, + avatar: organization.avatar_url, + visibility: organization.visibility, + }, + repositoryCount: repositories.length, + ...totals, + repositories: repositories + .slice() + .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at)) + .slice(0, 6) + .map((repository) => ({ + fullName: repository.full_name, + description: repository.description, + private: repository.private, + archived: repository.archived, + stars: repository.stars_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + updatedAt: repository.updated_at, + htmlUrl: repository.html_url, + })), + }; +} + +function recentEvents(limit = 15) { + return getDatabase() + .prepare('SELECT id, type, actor_id, payload, created_at FROM event_logs ORDER BY id DESC LIMIT ?') + .all(limit) + .map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null })); +} + +export function registerOverviewRoutes(router) { + router.get( + '/api/overview', + async ({ context }) => { + const id = guildId(); + const gitea = await giteaSnapshot(); + + return { + bot: botSnapshot(context.client, context.startedAt), + gitea, + database: databaseSnapshot(), + activity: { + openTickets: id ? countOpenTickets(id) : 0, + polls: id ? countPolls(id) : 0, + voiceChannels: id ? countVoiceChannels(id) : 0, + moderation: id ? countByAction(id) : [], + deployments: id ? countByStatus(id) : [], + environments: id ? lastDeploymentPerEnvironment(id) : [], + }, + events: recentEvents(), + features: { + webhooks: env.webhook.enabled, + commandDeploys: env.web.allowCommandDeploys, + restart: env.web.allowRestart, + gitea: isGiteaConfigured(), + }, + links: env.links, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/projects.js b/src/web/api/projects.js new file mode 100644 index 0000000..ce408b4 --- /dev/null +++ b/src/web/api/projects.js @@ -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 }, + ); +} diff --git a/src/web/api/releases.js b/src/web/api/releases.js new file mode 100644 index 0000000..2666680 --- /dev/null +++ b/src/web/api/releases.js @@ -0,0 +1,260 @@ +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { repos } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { notify } from '../../services/notifications/notification-service.js'; +import { badRequest } from '../http.js'; +import { runAutoDeployments } from '../services/deploy-service.js'; + +/** Release management, the publishing half of the SaaS pipeline (M16-T08). */ + +const log = createLogger('web:releases'); +const NAME = /^[\w.-]{1,100}$/; + +function target(params) { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); + const { owner, repo } = params; + if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.'); + return { owner, repo, fullName: `${owner}/${repo}` }; +} + +const summarize = (release) => ({ + id: release.id, + tag: release.tag_name, + name: release.name, + body: release.body, + draft: release.draft, + prerelease: release.prerelease, + target: release.target_commitish, + author: release.author?.login, + createdAt: release.created_at, + publishedAt: release.published_at, + htmlUrl: release.html_url, + assets: (release.assets ?? []).map((asset) => ({ + id: asset.id, + name: asset.name, + size: asset.size, + downloads: asset.download_count, + url: asset.browser_download_url, + })), +}); + +/** Same grouping as `scripts/generate-changelog.js`, applied to Gitea commits. */ +const SECTIONS = [ + { title: 'Nouveautés', test: (type) => type === 'feat' }, + { title: 'Corrections', test: (type) => type === 'fix' }, + { title: 'Performance', test: (type) => type === 'perf' }, + { title: 'Autres changements', test: (type) => !['feat', 'fix', 'perf'].includes(type) }, +]; + +const CONVENTIONAL = /^(?[a-z]+)(?:\((?[^)]*)\))?(?!)?: (?.+)$/; + +/** + * Builds release notes from the commits that follow the previous tag. + * Commits that do not follow Conventional Commits are kept verbatim, so nothing + * silently disappears from the notes. + */ +export function buildReleaseNotes(commits, { previousTag = null } = {}) { + const parsed = commits.map((commit) => { + const subject = (commit.commit?.message ?? '').split('\n')[0].trim(); + const match = CONVENTIONAL.exec(subject); + return { + subject, + sha: commit.sha?.slice(0, 8), + type: match?.groups.type ?? 'other', + scope: match?.groups.scope ?? null, + description: match?.groups.description ?? subject, + breaking: Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(commit.commit?.message ?? ''), + }; + }); + + const lines = []; + const breaking = parsed.filter((commit) => commit.breaking); + if (breaking.length > 0) { + lines.push('### ⚠ Changements incompatibles', ''); + for (const commit of breaking) lines.push(`- ${commit.description} (${commit.sha})`); + lines.push(''); + } + + for (const section of SECTIONS) { + const entries = parsed.filter((commit) => section.test(commit.type)); + if (entries.length === 0) continue; + lines.push(`### ${section.title}`, ''); + for (const commit of entries) { + const scope = commit.scope ? `**${commit.scope}** : ` : ''; + lines.push(`- ${scope}${commit.description} (${commit.sha})`); + } + lines.push(''); + } + + if (previousTag) lines.push(`_Changements depuis \`${previousTag}\`._`); + return lines.join('\n').trim() || '_Aucun changement détecté._'; +} + +export function registerReleaseRoutes(router) { + router.get( + '/api/repositories/:owner/:repo/releases', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listReleases(owner, repo, { + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + }); + return { releases: list.map(summarize) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo/tags', + async ({ params }) => { + const { owner, repo } = target(params); + const tags = await repos.listTags(owner, repo, { limit: 50 }).catch(() => []); + return { + tags: tags.map((tag) => ({ + name: tag.name, + sha: tag.commit?.sha?.slice(0, 8), + url: tag.zipball_url, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** Proposes release notes before the release is actually created. */ + router.post( + '/api/repositories/:owner/:repo/releases/notes', + async ({ params, body }) => { + const { owner, repo } = target(params); + const branch = String(body.target ?? '') || undefined; + const [commits, releases] = await Promise.all([ + repos.listCommits(owner, repo, { sha: branch, limit: 50 }), + repos.listReleases(owner, repo, { limit: 1 }).catch(() => []), + ]); + + const previous = releases[0] ?? null; + // Gitea has no "compare since tag" endpoint on every version, so the cut is + // made on the published date of the previous release. + const since = previous?.published_at ? new Date(previous.published_at) : null; + const selected = since + ? commits.filter((commit) => new Date(commit.commit?.author?.date ?? 0) > since) + : commits; + + return { + previousTag: previous?.tag_name ?? null, + commitCount: selected.length, + notes: buildReleaseNotes(selected, { previousTag: previous?.tag_name ?? null }), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/releases', + async ({ params, body, actor, context }) => { + const { owner, repo, fullName } = target(params); + const tagName = String(body.tag ?? '').trim(); + if (!/^[\w.\-+/]{1,64}$/.test(tagName)) throw badRequest('Nom de tag invalide.'); + + const release = await repos.createRelease(owner, repo, { + tagName, + target: body.target ? String(body.target) : undefined, + name: String(body.name ?? tagName), + body: String(body.body ?? ''), + draft: Boolean(body.draft), + prerelease: Boolean(body.prerelease), + }); + + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.create', + actorId: actor.userId, + payload: { repository: fullName, tag: tagName, draft: Boolean(body.draft) }, + }); + + // A draft is not public yet: no announcement, no deployment. + let deployments = []; + if (!release.draft) { + await announceRelease(context.client, fullName, release).catch((error) => + log.warn('Could not announce the release', error), + ); + if (body.deploy !== false) { + deployments = await runAutoDeployments(context.client, { + repository: fullName, + releaseTag: release.tag_name, + ref: release.target_commitish, + triggeredBy: actor.userId, + }); + } + } + + return { release: summarize(release), deployments }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/repositories/:owner/:repo/releases/:id', + async ({ params, body, actor, context }) => { + const { owner, repo, fullName } = target(params); + const id = Number.parseInt(params.id, 10); + + const before = await repos.getRelease(owner, repo, id); + const payload = {}; + if ('name' in body) payload.name = String(body.name); + if ('body' in body) payload.body = String(body.body); + if ('draft' in body) payload.draft = Boolean(body.draft); + if ('prerelease' in body) payload.prerelease = Boolean(body.prerelease); + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + const release = await repos.updateRelease(owner, repo, id, payload); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.update', + actorId: actor.userId, + payload: { repository: fullName, tag: release.tag_name }, + }); + + // Publishing a draft is the moment the release becomes real. + if (before.draft && !release.draft) { + await announceRelease(context.client, fullName, release).catch(() => null); + } + return summarize(release); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/repositories/:owner/:repo/releases/:id', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeRelease(owner, repo, Number.parseInt(params.id, 10)); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.delete', + actorId: actor.userId, + payload: { repository: fullName, id: params.id }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); +} + +function announceRelease(client, fullName, release) { + if (!client) return Promise.resolve(null); + + return notify(client, 'release', { + embeds: [ + { + title: `${release.name || release.tag_name} — ${fullName}`, + url: release.html_url, + color: release.prerelease ? COLORS.warning : COLORS.gitea, + description: String(release.body ?? '').slice(0, 1800) || 'Nouvelle version publiée.', + footer: { text: release.prerelease ? 'Préversion' : 'Version stable' }, + timestamp: release.published_at ?? new Date().toISOString(), + }, + ], + }); +} diff --git a/src/web/api/repositories.js b/src/web/api/repositories.js new file mode 100644 index 0000000..3497db9 --- /dev/null +++ b/src/web/api/repositories.js @@ -0,0 +1,541 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { org, repos } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { badRequest } from '../http.js'; + +/** Per-repository management (M16-T04). */ + +const NAME = /^[\w.-]{1,100}$/; + +function target(params) { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); + const { owner, repo } = params; + if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.'); + return { owner, repo, fullName: `${owner}/${repo}` }; +} + +const number = (value, field) => { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed) || parsed < 0) throw badRequest(`Valeur numérique attendue pour ${field}.`); + return parsed; +}; + +const audit = (actor, type, payload) => + logEvent({ guildId: env.discord.guildId || null, type, actorId: actor.userId, payload }); + +const summarizeIssue = (issue) => ({ + number: issue.number, + title: issue.title, + state: issue.state, + body: issue.body, + labels: (issue.labels ?? []).map((label) => ({ name: label.name, color: label.color })), + assignees: (issue.assignees ?? []).map((user) => user.login), + author: issue.user?.login, + authorAvatar: issue.user?.avatar_url, + comments: issue.comments, + createdAt: issue.created_at, + updatedAt: issue.updated_at, + closedAt: issue.closed_at, + milestone: issue.milestone?.title ?? null, + htmlUrl: issue.html_url, +}); + +const summarizePull = (pull) => ({ + ...summarizeIssue(pull), + draft: pull.draft, + mergeable: pull.mergeable, + merged: pull.merged, + mergedAt: pull.merged_at, + head: pull.head?.ref, + base: pull.base?.ref, + additions: pull.additions, + deletions: pull.deletions, + changedFiles: pull.changed_files, +}); + +export function registerRepositoryRoutes(router) { + router.get( + '/api/repositories', + async () => { + if (!isGiteaConfigured()) return { configured: false, repositories: [] }; + const list = await org.listRepos({ limit: 100 }); + return { + configured: true, + repositories: list.map((repository) => ({ + fullName: repository.full_name, + name: repository.name, + owner: repository.owner?.login, + description: repository.description, + private: repository.private, + archived: repository.archived, + defaultBranch: repository.default_branch, + language: repository.language, + stars: repository.stars_count, + forks: repository.forks_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + releases: repository.release_counter, + sizeKb: repository.size, + updatedAt: repository.updated_at, + htmlUrl: repository.html_url, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo', + async ({ params }) => { + const { owner, repo } = target(params); + const [details, branches, languages, topics, collaborators, release] = await Promise.all([ + repos.get(owner, repo), + repos.listBranches(owner, repo, { limit: 100 }).catch(() => []), + repos.languages(owner, repo).catch(() => ({})), + repos.listTopics(owner, repo).catch(() => ({ topics: [] })), + repos.listCollaborators(owner, repo).catch(() => []), + repos.latestRelease(owner, repo).catch(() => null), + ]); + + return { + fullName: details.full_name, + name: details.name, + owner: details.owner?.login, + description: details.description, + website: details.website, + private: details.private, + archived: details.archived, + template: details.template, + fork: details.fork, + mirror: details.mirror, + empty: details.empty, + defaultBranch: details.default_branch, + defaultMergeStyle: details.default_merge_style, + allowMergeCommits: details.allow_merge_commits, + allowRebase: details.allow_rebase, + allowSquash: details.allow_squash_merge, + hasIssues: details.has_issues, + hasPullRequests: details.has_pull_requests, + hasWiki: details.has_wiki, + hasActions: details.has_actions, + hasReleases: details.has_releases, + stars: details.stars_count, + forks: details.forks_count, + watchers: details.watchers_count, + openIssues: details.open_issues_count, + openPulls: details.open_pr_counter, + releases: details.release_counter, + sizeKb: details.size, + createdAt: details.created_at, + updatedAt: details.updated_at, + htmlUrl: details.html_url, + cloneUrl: details.clone_url, + sshUrl: details.ssh_url, + permissions: details.permissions, + languages, + topics: topics.topics ?? [], + branches: branches.map((branch) => ({ + name: branch.name, + protected: branch.protected, + commit: branch.commit?.id?.slice(0, 8), + commitMessage: branch.commit?.message?.split('\n')[0], + commitAt: branch.commit?.timestamp, + })), + collaborators: collaborators.map((user) => ({ + login: user.login, + fullName: user.full_name, + avatar: user.avatar_url, + permissions: user.permissions, + })), + latestRelease: release && { + tag: release.tag_name, + name: release.name, + publishedAt: release.published_at, + htmlUrl: release.html_url, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/repositories/:owner/:repo', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const allowed = [ + 'description', + 'website', + 'private', + 'archived', + 'default_branch', + 'default_merge_style', + 'has_issues', + 'has_pull_requests', + 'has_wiki', + 'has_actions', + 'has_releases', + 'allow_merge_commits', + 'allow_rebase', + 'allow_squash_merge', + ]; + const payload = Object.fromEntries(Object.entries(body).filter(([key]) => allowed.includes(key))); + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + await repos.update(owner, repo, payload); + audit(actor, 'web.repository.update', { repository: fullName, fields: Object.keys(payload) }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Deleting a repository is irreversible, so the full name must be typed back. */ + router.delete( + '/api/repositories/:owner/:repo', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + if (body.confirm !== fullName) { + throw badRequest(`Pour confirmer la suppression, renvoie exactement « ${fullName} ».`); + } + + await repos.remove(owner, repo); + audit(actor, 'web.repository.delete', { repository: fullName }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/repositories/:owner/:repo/topics', + async ({ params }) => { + const { owner, repo } = target(params); + return repos.listTopics(owner, repo); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/repositories/:owner/:repo/topics', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const topics = Array.isArray(body.topics) ? body.topics.map((topic) => String(topic).trim()) : null; + if (!topics) throw badRequest('`topics` doit être une liste.'); + + await repos.replaceTopics(owner, repo, topics); + audit(actor, 'web.repository.topics', { repository: fullName, topics }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Issues ---------------------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/issues', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listIssues(owner, repo, { + state: query.get('state') ?? 'open', + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + q: query.get('q') ?? undefined, + }); + return { issues: list.map(summarizeIssue) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/issues', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const title = String(body.title ?? '').trim(); + if (title.length < 3) throw badRequest('Le titre doit faire au moins 3 caractères.'); + + const issue = await repos.createIssue(owner, repo, { + title, + body: String(body.body ?? ''), + labels: body.labels ?? undefined, + assignees: body.assignees ?? undefined, + }); + audit(actor, 'web.issue.create', { repository: fullName, number: issue.number }); + return summarizeIssue(issue); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/repositories/:owner/:repo/issues/:number', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const issueNumber = number(params.number, 'number'); + + const payload = {}; + if ('state' in body) { + if (!['open', 'closed'].includes(body.state)) throw badRequest('État attendu : open ou closed.'); + payload.state = body.state; + } + for (const field of ['title', 'body', 'assignees', 'labels', 'milestone']) { + if (field in body) payload[field] = body[field]; + } + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + const issue = await repos.updateIssue(owner, repo, issueNumber, payload); + audit(actor, 'web.issue.update', { + repository: fullName, + number: issueNumber, + fields: Object.keys(payload), + }); + return summarizeIssue(issue); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/issues/:number/comments', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const issueNumber = number(params.number, 'number'); + const message = String(body.body ?? '').trim(); + if (message === '') throw badRequest('Le commentaire est vide.'); + + const comment = await repos.commentIssue(owner, repo, issueNumber, message); + audit(actor, 'web.issue.comment', { repository: fullName, number: issueNumber }); + return { id: comment.id, htmlUrl: comment.html_url }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo/labels', + async ({ params }) => { + const { owner, repo } = target(params); + return { labels: await repos.listLabels(owner, repo) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Pull requests --------------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/pulls', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listPulls(owner, repo, { + state: query.get('state') ?? 'open', + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + }); + return { pulls: list.map(summarizePull) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/pulls', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const { title, head, base } = body; + if (!title || !head || !base) throw badRequest('`title`, `head` et `base` sont obligatoires.'); + + const pull = await repos.createPull(owner, repo, { + title: String(title), + body: String(body.body ?? ''), + head: String(head), + base: String(base), + }); + audit(actor, 'web.pull.create', { repository: fullName, number: pull.number }); + return summarizePull(pull); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/pulls/:number/merge', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const pullNumber = number(params.number, 'number'); + const style = String(body.style ?? 'squash'); + if (!['merge', 'rebase', 'rebase-merge', 'squash'].includes(style)) { + throw badRequest('Méthode de merge inconnue.'); + } + + await repos.mergePull(owner, repo, pullNumber, { + style, + title: body.title ? String(body.title) : undefined, + message: body.message ? String(body.message) : undefined, + deleteBranch: Boolean(body.deleteBranch), + }); + audit(actor, 'web.pull.merge', { repository: fullName, number: pullNumber, style }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Branches and commits -------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/commits', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listCommits(owner, repo, { + sha: query.get('branch') ?? undefined, + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '25', 10), 50), + }); + return { + commits: list.map((commit) => ({ + sha: commit.sha, + shortSha: commit.sha?.slice(0, 8), + message: commit.commit?.message?.split('\n')[0], + author: commit.commit?.author?.name, + authorLogin: commit.author?.login, + avatar: commit.author?.avatar_url, + date: commit.commit?.author?.date, + htmlUrl: commit.html_url, + stats: commit.stats, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/branches', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const newBranchName = String(body.name ?? '').trim(); + if (newBranchName === '') throw badRequest('Nom de branche manquant.'); + + const branch = await repos.createBranch(owner, repo, { + newBranchName, + oldBranchName: body.from ? String(body.from) : undefined, + }); + audit(actor, 'web.branch.create', { repository: fullName, branch: newBranchName }); + return { name: branch.name }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/repositories/:owner/:repo/branches', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const branch = String(body.name ?? '').trim(); + if (branch === '') throw badRequest('Nom de branche manquant.'); + + await repos.removeBranch(owner, repo, branch); + audit(actor, 'web.branch.delete', { repository: fullName, branch }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Collaborators --------------------------------------------------------- + router.put( + '/api/repositories/:owner/:repo/collaborators/:username', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const permission = String(body.permission ?? 'write'); + if (!['read', 'write', 'admin'].includes(permission)) throw badRequest('Permission inconnue.'); + + await repos.addCollaborator(owner, repo, params.username, permission); + audit(actor, 'web.collaborator.add', { repository: fullName, user: params.username, permission }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/repositories/:owner/:repo/collaborators/:username', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeCollaborator(owner, repo, params.username); + audit(actor, 'web.collaborator.remove', { repository: fullName, user: params.username }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- Webhooks and actions -------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/hooks', + async ({ params }) => { + const { owner, repo } = target(params); + const hooks = await repos.listHooks(owner, repo).catch(() => []); + return { + hooks: hooks.map((hook) => ({ + id: hook.id, + type: hook.type, + active: hook.active, + events: hook.events, + url: hook.config?.url, + createdAt: hook.created_at, + })), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** + * Convenience route: wires Gitea to this bot's own webhook endpoint with the + * secret already configured, which is the step people most often get wrong. + */ + router.post( + '/api/repositories/:owner/:repo/hooks', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const url = String(body.url ?? '').trim() || `${env.web.publicUrl}${env.webhook.path}`; + if (!url.startsWith('http')) throw badRequest('URL de webhook invalide.'); + + const secret = String(body.secret ?? '') || env.webhook.secret; + if (!secret) throw badRequest('Aucun secret disponible : renseigne `GITEA_WEBHOOK_SECRET`.'); + + const hook = await repos.createHook(owner, repo, { + url, + secret, + events: body.events ?? ['issues', 'pull_request', 'push', 'release'], + }); + audit(actor, 'web.hook.create', { repository: fullName, url }); + return { id: hook.id, url }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/repositories/:owner/:repo/hooks/:id', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeHook(owner, repo, number(params.id, 'id')); + audit(actor, 'web.hook.delete', { repository: fullName, hook: params.id }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/repositories/:owner/:repo/actions', + async ({ params }) => { + const { owner, repo } = target(params); + // Gitea Actions is absent before 1.20 and returns 404 when disabled on the repo. + const payload = await repos.listActionTasks(owner, repo, { limit: 20 }).catch(() => null); + if (!payload) return { available: false, tasks: [] }; + + const tasks = Array.isArray(payload) ? payload : (payload.workflow_runs ?? payload.data ?? []); + return { + available: true, + tasks: tasks.map((task) => ({ + id: task.id, + name: task.name, + headBranch: task.head_branch, + headSha: task.head_sha?.slice(0, 8), + status: task.status, + conclusion: task.conclusion, + event: task.event, + runNumber: task.run_number, + createdAt: task.created_at, + updatedAt: task.updated_at, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/search.js b/src/web/api/search.js new file mode 100644 index 0000000..62aea79 --- /dev/null +++ b/src/web/api/search.js @@ -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 }, + ); +} diff --git a/src/web/api/settings.js b/src/web/api/settings.js new file mode 100644 index 0000000..c6a5fcb --- /dev/null +++ b/src/web/api/settings.js @@ -0,0 +1,308 @@ +import { randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import path from 'node:path'; +import { + ACCESS_LABELS, + ACCESS_LEVELS, + NOTIFICATION_TYPES, + TICKET_CATEGORIES, +} from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { getDatabase } from '../../database/index.js'; +import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js'; +import { GUILD_SETTINGS, SETTING_SECTIONS, allSettings, writeSetting } from '../../config/guild-settings.js'; +import { + createApiToken, + deleteSession, + listApiTokens, + listSessions, + purgeExpiredSessions, + revokeApiToken, +} from '../../database/repositories/web-session-repository.js'; +import { org } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { badRequest, forbidden, notFound } from '../http.js'; +import { hashToken } from '../auth/session.js'; +import { isOauthConfigured, redirectUri } from '../auth/discord-oauth.js'; + +/** Everything the settings tab needs (M16-T10). */ + +const log = createLogger('web:settings'); +const guildId = () => env.discord.guildId; + +const readManaged = () => { + try { + return allSettings(guildId()); + } catch { + // The database is not ready: fall back to the declared defaults. + return Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting.default])); + } +}; + +export function registerSettingsRoutes(router) { + router.get( + '/api/settings', + ({ request, actor }) => ({ + schema: GUILD_SETTINGS, + sections: SETTING_SECTIONS, + values: readManaged(), + runtime: { + nodeEnv: env.nodeEnv, + logLevel: env.logLevel, + logDir: env.logDir, + logRetentionDays: env.logRetentionDays, + databasePath: env.database.path, + backupDir: env.database.backupDir, + nodeVersion: process.version, + pid: process.pid, + }, + discord: { + clientId: env.discord.clientId, + guildId: env.discord.guildId, + roles: env.roles, + channels: env.channels, + tokenConfigured: Boolean(env.discord.token), + }, + gitea: { + configured: isGiteaConfigured(), + url: env.gitea.url, + owner: env.gitea.owner, + repo: env.gitea.repo, + repositoryUrl: repositoryUrl(), + timeoutMs: env.gitea.timeoutMs, + maxRetries: env.gitea.maxRetries, + tokenConfigured: Boolean(env.gitea.token), + }, + webhook: { + enabled: env.webhook.enabled, + host: env.webhook.host, + port: env.webhook.port, + path: env.webhook.path, + secretConfigured: Boolean(env.webhook.secret), + publicUrl: env.web.publicUrl ? `${env.web.publicUrl}${env.webhook.path}` : null, + }, + web: { + enabled: env.web.enabled, + host: env.web.host, + port: env.web.port, + publicUrl: env.web.publicUrl, + sessionTtlHours: env.web.sessionTtlHours, + oauthConfigured: isOauthConfigured(), + redirectUri: redirectUri(request), + allowCommandDeploys: env.web.allowCommandDeploys, + allowRestart: env.web.allowRestart, + rateLimitPerMinute: env.web.rateLimitPerMinute, + }, + reference: { + notificationTypes: NOTIFICATION_TYPES, + ticketCategories: TICKET_CATEGORIES, + accessLevels: Object.entries(ACCESS_LEVELS).map(([name, value]) => ({ + name, + value, + label: ACCESS_LABELS[value], + })), + }, + viewer: { accessLevel: actor.accessLevel, accessLabel: ACCESS_LABELS[actor.accessLevel] }, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/settings/values/:key', + ({ params, body, actor }) => { + if (!GUILD_SETTINGS.some((setting) => setting.key === params.key)) throw notFound('Réglage inconnu.'); + + let value; + try { + value = writeSetting(params.key, body.value, { guildId: guildId(), updatedBy: actor.userId }); + } catch (error) { + throw badRequest(error.message); + } + + logEvent({ + guildId: guildId(), + type: 'web.settings.update', + actorId: actor.userId, + payload: { key: params.key, value }, + }); + return { key: params.key, value }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Sessions -------------------------------------------------------------- + router.get( + '/api/settings/sessions', + ({ actor }) => ({ + sessions: listSessions().map((session) => ({ + ...session, + accessLabel: ACCESS_LABELS[session.access_level], + current: session.id === actor.sessionId, + })), + }), + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/settings/sessions/:id', + ({ params, actor }) => { + if (params.id === actor.sessionId) + throw badRequest('Utilise la déconnexion pour fermer ta propre session.'); + const removed = deleteSession(params.id); + if (removed === 0) throw notFound('Session introuvable.'); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- API tokens ------------------------------------------------------------ + router.get( + '/api/settings/tokens', + () => ({ + tokens: listApiTokens().map((token) => ({ + ...token, + accessLabel: ACCESS_LABELS[token.access_level], + active: !token.revoked_at, + })), + }), + { access: ACCESS_LEVELS.OWNER }, + ); + + /** The clear token is shown once and never stored, only its hash is kept. */ + router.post( + '/api/settings/tokens', + ({ body, actor }) => { + const name = String(body.name ?? '').trim(); + if (!/^[\w .-]{3,60}$/.test(name)) throw badRequest('Nom de jeton invalide (3 à 60 caractères).'); + + const accessLevel = Number.parseInt(body.accessLevel ?? ACCESS_LEVELS.STAFF, 10); + if (!Object.values(ACCESS_LEVELS).includes(accessLevel)) throw badRequest('Niveau d’accès inconnu.'); + if (accessLevel > actor.accessLevel) + throw forbidden('Tu ne peux pas créer un jeton plus puissant que toi.'); + + const token = `fws_${randomBytes(24).toString('base64url')}`; + const id = createApiToken({ + name, + tokenHash: hashToken(token), + prefix: token.slice(0, 12), + accessLevel, + createdBy: actor.userId, + expiresAt: body.expiresAt ? String(body.expiresAt) : null, + }); + + logEvent({ + guildId: guildId(), + type: 'web.token.create', + actorId: actor.userId, + payload: { id, name, accessLevel }, + }); + return { id, name, accessLevel, token }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/settings/tokens/:id', + ({ params, actor }) => { + const revoked = revokeApiToken(Number.parseInt(params.id, 10)); + if (revoked === 0) throw notFound('Jeton introuvable ou déjà révoqué.'); + logEvent({ + guildId: guildId(), + type: 'web.token.revoke', + actorId: actor.userId, + payload: { id: params.id }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- Maintenance ----------------------------------------------------------- + router.post( + '/api/settings/backup', + ({ actor }) => { + mkdirSync(env.database.backupDir, { recursive: true }); + const file = path.join( + env.database.backupDir, + `fws-bot-${new Date().toISOString().replace(/[:.]/g, '-')}.sqlite`, + ); + // `VACUUM INTO` produces a consistent copy even with the WAL journal active. + getDatabase().exec(`VACUUM INTO '${file.replaceAll("'", "''")}'`); + + logEvent({ guildId: guildId(), type: 'web.backup', actorId: actor.userId, payload: { file } }); + log.info('Database backup written', { file }); + return { file }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.post( + '/api/settings/purge', + ({ body, actor }) => { + const days = Number.parseInt(body.days ?? env.logRetentionDays, 10); + if (!Number.isInteger(days) || days < 1) throw badRequest('Nombre de jours invalide.'); + + const events = purgeEventsOlderThan(days); + const sessions = purgeExpiredSessions(); + logEvent({ + guildId: guildId(), + type: 'web.purge', + actorId: actor.userId, + payload: { days, events, sessions }, + }); + return { events, sessions }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + /** Checks the credentials without revealing them. */ + router.post( + '/api/settings/test/:service', + async ({ params, context }) => { + if (params.service === 'discord') { + const client = context.client; + return { + ok: Boolean(client?.isReady?.()), + detail: client?.isReady?.() + ? `Connecté en tant que ${client.user.tag}, ping ${client.ws.ping} ms.` + : 'Le bot n’est pas connecté à Discord.', + }; + } + + if (params.service === 'gitea') { + if (!isGiteaConfigured()) return { ok: false, detail: 'GITEA_URL ou GITEA_TOKEN manquant.' }; + try { + const user = await org.whoami(); + const organization = await org.get().catch(() => null); + return { + ok: true, + detail: `Jeton valide pour « ${user.login} »${organization ? `, accès à l’organisation « ${organization.username ?? organization.name} »` : ', mais l’organisation est inaccessible'}.`, + }; + } catch (error) { + return { ok: false, detail: `Échec de l’appel Gitea : ${error.message}` }; + } + } + + throw notFound('Service inconnu.'); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** + * Stops the process so a supervisor restarts it. Without one, the bot simply + * stops, which is why the capability is disabled by default. + */ + router.post( + '/api/settings/restart', + ({ actor }) => { + if (!env.web.allowRestart) throw forbidden('Le redémarrage est désactivé (`WEB_ALLOW_RESTART`).'); + + logEvent({ guildId: guildId(), type: 'web.restart', actorId: actor.userId, payload: null }); + log.warn('Restart requested from the dashboard', { actor: actor.userId }); + setTimeout(() => process.exit(0), 500).unref(); + return { ok: true, message: 'Redémarrage dans un instant…' }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); +} diff --git a/src/web/api/status.js b/src/web/api/status.js new file mode 100644 index 0000000..d530aa6 --- /dev/null +++ b/src/web/api/status.js @@ -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 }, + ); +} diff --git a/src/web/api/wiki.js b/src/web/api/wiki.js new file mode 100644 index 0000000..ccd41ae --- /dev/null +++ b/src/web/api/wiki.js @@ -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 }, + ); +} diff --git a/src/web/auth/discord-oauth.js b/src/web/auth/discord-oauth.js new file mode 100644 index 0000000..9223c1a --- /dev/null +++ b/src/web/auth/discord-oauth.js @@ -0,0 +1,143 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { ExternalApiError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; + +const log = createLogger('web:oauth'); +const DISCORD_API = 'https://discord.com/api/v10'; + +/** + * `identify` names the visitor, `guilds.members.read` reads their roles on the FWS + * guild so the dashboard can apply the very same access levels as the slash + * commands (M16-T02). + */ +const SCOPES = ['identify', 'guilds.members.read']; + +/** + * Origin the visitor actually reached the dashboard on. + * + * It is the address in their browser bar that has to match the redirect + * declared in the Developer Portal, and a hosting panel or a proxy commonly + * publishes the site on a different port than `WEB_PUBLIC_URL` claims. + * Trusting the request rather than the configuration avoids a sign-in that + * fails on a port mismatch nobody thinks to look at. + */ +export function requestOrigin(request) { + const header = (name) => + String(request?.headers?.[name] ?? '') + .split(',')[0] + .trim(); + + const host = header('x-forwarded-host') || header('host'); + if (!host) return env.web.publicUrl; + + const protocol = header('x-forwarded-proto') || (request.socket?.encrypted ? 'https' : 'http'); + return `${protocol}://${host}`; +} + +export const redirectUri = (request) => { + const origin = requestOrigin(request) || env.web.publicUrl; + return origin ? `${origin}/auth/callback` : ''; +}; + +/** + * True when the OAuth2 login can run. `WEB_PUBLIC_URL` is not required: the + * redirect is derived from the request when one is available. + */ +export function isOauthConfigured() { + return Boolean(env.discord.clientId && env.web.oauthClientSecret); +} + +export function authorizeUrl(state, request) { + const params = new URLSearchParams({ + client_id: env.discord.clientId, + response_type: 'code', + redirect_uri: redirectUri(request), + scope: SCOPES.join(' '), + state, + prompt: 'none', + }); + return `https://discord.com/oauth2/authorize?${params}`; +} + +async function discordFetch(endpoint, options = {}) { + const response = await fetch(`${DISCORD_API}${endpoint}`, { + ...options, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { + const error = new ExternalApiError('discord', `${endpoint} failed with ${response.status}`); + error.status = response.status; + throw error; + } + return response.status === 204 ? null : response.json(); +} + +/** Discord checks that this `redirect_uri` is the one used to obtain the code. */ +export async function exchangeCode(code, request) { + const body = new URLSearchParams({ + client_id: env.discord.clientId, + client_secret: env.web.oauthClientSecret, + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri(request), + }); + + return discordFetch('/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); +} + +/** Best effort cleanup: the dashboard never needs the user token again. */ +export async function revokeToken(accessToken) { + const body = new URLSearchParams({ + client_id: env.discord.clientId, + client_secret: env.web.oauthClientSecret, + token: accessToken, + }); + await discordFetch('/oauth2/token/revoke', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }).catch((error) => log.debug('Token revocation failed', error)); +} + +export function fetchUser(accessToken) { + return discordFetch('/users/@me', { headers: { Authorization: `Bearer ${accessToken}` } }); +} + +/** Returns null when the visitor is not a member of the guild. */ +export async function fetchGuildMember(accessToken, guildId) { + try { + return await discordFetch(`/users/@me/guilds/${guildId}/member`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + } catch (error) { + if (error.status === 404 || error.status === 403) return null; + throw error; + } +} + +/** + * Same ladder as `core/permissions.js`, applied to the raw role ids returned by + * the OAuth2 member endpoint (which has no discord.js `GuildMember` to offer). + */ +export function resolveAccessLevel({ member, userId, guildOwnerId, roles = env.roles }) { + if (userId && guildOwnerId && userId === guildOwnerId) return ACCESS_LEVELS.OWNER; + if (!member) return null; + + const owned = new Set(member.roles ?? []); + const has = (roleId) => Boolean(roleId) && owned.has(roleId); + if (has(roles.owner)) return ACCESS_LEVELS.OWNER; + if (has(roles.dev)) return ACCESS_LEVELS.DEV; + if (has(roles.staff)) return ACCESS_LEVELS.STAFF; + return ACCESS_LEVELS.USER; +} + +export function avatarUrl(user) { + if (!user?.id) return null; + if (!user.avatar) return `https://cdn.discordapp.com/embed/avatars/${(BigInt(user.id) >> 22n) % 6n}.png`; + return `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128`; +} diff --git a/src/web/auth/guard.js b/src/web/auth/guard.js new file mode 100644 index 0000000..9320ae8 --- /dev/null +++ b/src/web/auth/guard.js @@ -0,0 +1,30 @@ +import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; +import { forbidden, unauthorized } from '../http.js'; + +/** + * Route level access control (M16-T03). + * + * A route declares `{ access: ACCESS_LEVELS.DEV }`. Two exceptions exist: + * - `public: true` skips authentication entirely (login page, health check); + * - `setup: true` marks the routes a bootstrap session may reach. Bootstrap + * sessions exist before Discord is configured, so they are deliberately + * confined to the configuration wizard. + */ +export function authorize(actor, options = {}) { + if (options.public) return; + + if (!actor) throw unauthorized(); + + if (actor.source === 'setup' && !options.setup) { + throw forbidden("Session d'amorçage : seule la configuration est accessible"); + } + + const required = options.access ?? ACCESS_LEVELS.OWNER; + if (actor.accessLevel < required) { + throw forbidden(`Niveau ${ACCESS_LABELS[required]} requis pour cette action`); + } +} + +export function canReach(accessLevel, required) { + return accessLevel >= required; +} diff --git a/src/web/auth/routes.js b/src/web/auth/routes.js new file mode 100644 index 0000000..8a7ceaa --- /dev/null +++ b/src/web/auth/routes.js @@ -0,0 +1,161 @@ +import { randomBytes } from 'node:crypto'; +import { ACCESS_LABELS, ACCESS_LEVELS } 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 { appendCookie, forbidden, parseCookies, redirect, serializeCookie } from '../http.js'; +import { hasSetupToken, isSetupTokenValid } from '../setup-state.js'; +import { + authorizeUrl, + avatarUrl, + exchangeCode, + fetchGuildMember, + fetchUser, + isOauthConfigured, + redirectUri, + resolveAccessLevel, + revokeToken, +} from './discord-oauth.js'; +import { STATE_COOKIE, closeSession, openSession, secureCookies, signState, verifyState } from './session.js'; + +const log = createLogger('web:auth'); + +/** Registers the login, callback, logout and identity routes (M16-T02). */ +export function registerAuthRoutes(router) { + router.get( + '/api/auth/config', + ({ request, context }) => ({ + oauthConfigured: isOauthConfigured(), + setupAvailable: hasSetupToken(), + setupOnly: context.setupOnly, + guildConfigured: Boolean(env.discord.guildId), + loginUrl: '/auth/login', + // Shown on the sign-in page: it is the value to declare in the portal. + redirectUri: redirectUri(request), + }), + { public: true }, + ); + + router.get( + '/auth/login', + ({ request, response }) => { + if (!isOauthConfigured()) { + redirect(response, '/#/login?error=oauth-not-configured'); + return; + } + const state = signState(randomBytes(16).toString('base64url')); + appendCookie( + response, + serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies(request) }), + ); + redirect(response, authorizeUrl(state, request)); + }, + { public: true }, + ); + + router.get( + '/auth/callback', + async ({ request, response, query, context }) => { + const failure = (reason) => redirect(response, `/#/login?error=${reason}`); + + if (query.get('error')) return failure(query.get('error')); + + const state = query.get('state'); + const expected = parseCookies(request.headers.cookie)[STATE_COOKIE]; + appendCookie( + response, + serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies(request) }), + ); + if (!state || state !== expected || !verifyState(state)) return failure('state-mismatch'); + + const code = query.get('code'); + if (!code) return failure('missing-code'); + + let grant; + try { + grant = await exchangeCode(code, request); + } catch (error) { + log.warn('OAuth2 code exchange failed', { error, redirectUri: redirectUri(request) }); + return failure('exchange-failed'); + } + + const user = await fetchUser(grant.access_token); + const member = await fetchGuildMember(grant.access_token, env.discord.guildId); + await revokeToken(grant.access_token); + + const guildOwnerId = context.client?.guilds?.cache?.get(env.discord.guildId)?.ownerId ?? null; + const accessLevel = resolveAccessLevel({ member, userId: user.id, guildOwnerId }); + + if (accessLevel === null) { + log.warn('Login refused, user is not a member of the guild', { userId: user.id }); + return failure('not-a-member'); + } + if (accessLevel < ACCESS_LEVELS.STAFF) { + log.warn('Login refused, insufficient level', { userId: user.id, accessLevel }); + return failure('insufficient-level'); + } + + openSession(request, response, { + user: { + id: user.id, + username: user.username, + displayName: member?.nick || user.global_name || user.username, + avatar: avatarUrl(user), + }, + accessLevel, + }); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.login', + actorId: user.id, + payload: { accessLevel }, + }); + redirect(response, '/#/'); + }, + { public: true }, + ); + + /** + * Bootstrap login. Only opens a session confined to the configuration wizard, + * never a full dashboard session (M16-T09). + */ + router.post( + '/api/auth/setup', + ({ request, response, body }) => { + if (!hasSetupToken()) throw forbidden("Aucun jeton d'amorçage n'est configuré"); + if (!isSetupTokenValid(body.token)) throw forbidden("Jeton d'amorçage invalide"); + + openSession(request, response, { + user: { id: null, username: 'setup', displayName: 'Assistant de configuration' }, + accessLevel: ACCESS_LEVELS.OWNER, + source: 'setup', + }); + return { ok: true, source: 'setup' }; + }, + { public: true }, + ); + + router.post('/api/auth/logout', ({ request, response }) => { + closeSession(request, response); + return { ok: true }; + }); + + router.get( + '/api/me', + ({ actor }) => { + if (!actor) return { authenticated: false }; + return { + authenticated: true, + userId: actor.userId, + username: actor.username, + displayName: actor.displayName, + avatar: actor.avatar, + accessLevel: actor.accessLevel, + accessLabel: ACCESS_LABELS[actor.accessLevel], + source: actor.source, + kind: actor.kind, + }; + }, + { public: true }, + ); +} diff --git a/src/web/auth/session.js b/src/web/auth/session.js new file mode 100644 index 0000000..1e47550 --- /dev/null +++ b/src/web/auth/session.js @@ -0,0 +1,183 @@ +import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { + createSession, + deleteSession, + getLiveApiTokenByHash, + getLiveSessionByHash, + purgeExpiredSessions, + touchApiToken, + touchSession, +} from '../../database/repositories/web-session-repository.js'; +import { appendCookie, clientIp, forbidden, parseCookies, serializeCookie } from '../http.js'; + +const log = createLogger('web:auth'); + +export const SESSION_COOKIE = 'fws_session'; +export const STATE_COOKIE = 'fws_oauth_state'; + +/** + * Peppers the session tokens. Without `WEB_SESSION_SECRET` a random key is used, + * which keeps the dashboard usable but logs everyone out on restart. + */ +const pepper = (() => { + if (env.web.sessionSecret) return env.web.sessionSecret; + log.warn('WEB_SESSION_SECRET is not set: sessions will be dropped on every restart'); + return randomBytes(32).toString('hex'); +})(); + +const hash = (value) => createHmac('sha256', pepper).update(value).digest('hex'); + +/** + * A `Secure` cookie is dropped by the browser over plain HTTP, so the flag has + * to follow the scheme the visitor actually used rather than what the + * configuration announces. + */ +export const secureCookies = (request) => { + const forwarded = String(request?.headers?.['x-forwarded-proto'] ?? '') + .split(',')[0] + .trim(); + if (forwarded) return forwarded === 'https'; + if (request?.socket?.encrypted) return true; + return env.web.publicUrl.startsWith('https://'); +}; + +export function issueToken() { + return randomBytes(32).toString('base64url'); +} + +/** Signs the OAuth2 `state` so the callback can prove it started the flow. */ +export function signState(value) { + return `${value}.${createHmac('sha256', pepper).update(value).digest('base64url')}`; +} + +export function verifyState(signed) { + const separator = String(signed ?? '').lastIndexOf('.'); + if (separator < 0) return null; + const value = signed.slice(0, separator); + const expected = Buffer.from(createHmac('sha256', pepper).update(value).digest('base64url')); + const received = Buffer.from(signed.slice(separator + 1)); + if (expected.length !== received.length || !timingSafeEqual(expected, received)) return null; + return value; +} + +export function openSession(request, response, { user = {}, accessLevel, source = 'discord' }) { + purgeExpiredSessions(); + + const token = issueToken(); + const ttlSeconds = Math.max(1, env.web.sessionTtlHours) * 3600; + const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19); + + const session = createSession({ + id: randomUUID(), + tokenHash: hash(token), + userId: user.id ?? null, + username: user.username ?? null, + displayName: user.displayName ?? user.global_name ?? user.username ?? null, + avatar: user.avatar ?? null, + accessLevel, + source, + ip: clientIp(request), + userAgent: String(request.headers['user-agent'] ?? '').slice(0, 255), + expiresAt, + }); + + appendCookie( + response, + serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies(request) }), + ); + log.info('Dashboard session opened', { userId: session.user_id, source, accessLevel }); + return session; +} + +export function closeSession(request, response) { + const token = parseCookies(request.headers.cookie)[SESSION_COOKIE]; + const session = token ? getLiveSessionByHash(hash(token)) : null; + if (session) deleteSession(session.id); + appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies(request) })); +} + +/** + * Identifies the caller from its session cookie or its `Authorization: Bearer` token. + * Returns null for anonymous requests, the route guard decides what to do with it. + */ +export function authenticate(request) { + const token = parseCookies(request.headers.cookie)[SESSION_COOKIE]; + if (token) { + const session = getLiveSessionByHash(hash(token)); + if (session) { + touchSession(session.id); + return { + kind: 'session', + sessionId: session.id, + userId: session.user_id, + username: session.username, + displayName: session.display_name, + avatar: session.avatar, + accessLevel: session.access_level, + source: session.source, + }; + } + } + + const header = String(request.headers.authorization ?? ''); + if (header.startsWith('Bearer ')) { + const apiToken = getLiveApiTokenByHash(hash(header.slice(7).trim())); + if (apiToken) { + touchApiToken(apiToken.id); + return { + kind: 'api-token', + userId: apiToken.created_by, + username: apiToken.name, + displayName: apiToken.name, + accessLevel: apiToken.access_level, + source: 'token', + }; + } + } + + return null; +} + +export const hashToken = hash; + +/** + * Blocks cross-site writes. Cookies are `SameSite=Lax`, so a cross-origin POST + * cannot carry them; the custom header adds a second barrier that a form post + * cannot forge, and the `Origin` check covers the rest (M16-T02). + */ +export function assertSameOrigin(request, actor) { + if (request.method === 'GET' || request.method === 'HEAD') return; + if (actor?.kind === 'api-token') return; + + if (request.headers['x-requested-with'] !== 'fws-dashboard') { + throw forbidden('Requête rejetée : en-tête X-Requested-With manquant'); + } + + const origin = request.headers.origin; + if (!origin) return; + + // The host the visitor used is what the browser puts in `Origin`; behind a + // proxy that is the forwarded one, not the socket's. + const hosts = [request.headers['x-forwarded-host'], request.headers.host] + .map((value) => + String(value ?? '') + .split(',')[0] + .trim(), + ) + .filter(Boolean); + const allowed = new Set([ + env.web.publicUrl, + ...hosts.flatMap((host) => [`http://${host}`, `https://${host}`]), + ]); + + if (!allowed.has(origin.replace(/\/+$/, ''))) { + throw forbidden('Requête rejetée : origine inattendue'); + } +} + +export const LEVEL_NAMES = Object.freeze( + Object.fromEntries(Object.entries(ACCESS_LEVELS).map(([name, value]) => [value, name])), +); diff --git a/src/web/events.js b/src/web/events.js new file mode 100644 index 0000000..438bb25 --- /dev/null +++ b/src/web/events.js @@ -0,0 +1,137 @@ +import { createLogger } from '../core/logger.js'; + +/** + * Server-sent events feeding the dashboard live (M16-T12). + * + * One long-lived GET per open tab, pushed to rather than polled: a browser that + * nobody is looking at costs a heartbeat every 25 seconds, and a change shows up + * as soon as it happens instead of on the next timer. + */ + +const log = createLogger('web:events'); + +const HEARTBEAT_MS = 25_000; +const TICK_MS = 15_000; +/** Past this, something is wrong: refuse rather than pile up dead sockets. */ +const MAX_SUBSCRIBERS = 64; + +const subscribers = new Set(); +let heartbeat = null; +let tick = null; + +function write(subscriber, payload) { + try { + subscriber.response.write(payload); + } catch (error) { + log.debug('Dropping a closed event subscriber', error); + remove(subscriber); + } +} + +function remove(subscriber) { + if (!subscribers.delete(subscriber)) return; + try { + subscriber.response.end(); + } catch { + // The socket is already gone, which is exactly why we are here. + } + if (subscribers.size === 0) stopTimers(); +} + +function startTimers() { + if (heartbeat) return; + // Comment frames keep proxies from closing an idle stream. + heartbeat = setInterval(() => { + for (const subscriber of subscribers) write(subscriber, ': ping\n\n'); + }, HEARTBEAT_MS); + tick = setInterval(() => broadcast('tick', { at: new Date().toISOString() }), TICK_MS); + + // Timers must never be the reason the process stays alive. + heartbeat.unref?.(); + tick.unref?.(); +} + +function stopTimers() { + clearInterval(heartbeat); + clearInterval(tick); + heartbeat = null; + tick = null; +} + +/** Publishes an event to every open dashboard. Never throws. */ +export function broadcast(topic, payload = {}) { + if (subscribers.size === 0) return 0; + + const frame = `event: ${topic}\ndata: ${JSON.stringify({ topic, ...payload })}\n\n`; + for (const subscriber of subscribers) write(subscriber, frame); + return subscribers.size; +} + +/** + * Registers a subscriber and keeps the response open. + * Returns nothing: the router must not try to serialise a body onto it. + */ +export function openEventStream(request, response, actor) { + if (subscribers.size >= MAX_SUBSCRIBERS) { + response.writeHead(503).end(); + return; + } + + response.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + // `no-transform` and the nginx hint both matter: a buffering proxy turns a + // live stream into a stream that arrives all at once, much later. + 'Cache-Control': 'no-cache, no-transform', + 'X-Accel-Buffering': 'no', + Connection: 'keep-alive', + 'X-Content-Type-Options': 'nosniff', + }); + response.flushHeaders?.(); + + const subscriber = { response, userId: actor?.userId ?? null }; + subscribers.add(subscriber); + startTimers(); + + write(subscriber, `retry: 5000\nevent: ready\ndata: ${JSON.stringify({ topic: 'ready' })}\n\n`); + + request.on('close', () => remove(subscriber)); + request.on('error', () => remove(subscriber)); + log.debug('Event subscriber connected', { subscribers: subscribers.size }); +} + +export function subscriberCount() { + return subscribers.size; +} + +/** Closes every stream, so a shutdown does not hang on open sockets. */ +export function closeEventStreams() { + for (const subscriber of [...subscribers]) remove(subscriber); + stopTimers(); +} + +/** + * Turns an API path into the topic a view can filter on, so a write made + * anywhere refreshes the pages that care and only those. + */ +export function topicForPath(pathname) { + const [, , section] = pathname.split('/'); + switch (section) { + case 'deploy': + case 'deployments': + return 'deployments'; + case 'repositories': + case 'organization': + return 'gitea'; + case 'projects': + return 'projects'; + case 'discord': + return 'discord'; + case 'community': + return 'community'; + case 'settings': + case 'configuration': + return 'settings'; + default: + return 'mutation'; + } +} diff --git a/src/web/http.js b/src/web/http.js new file mode 100644 index 0000000..9b00fa3 --- /dev/null +++ b/src/web/http.js @@ -0,0 +1,198 @@ +import { createReadStream } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import path from 'node:path'; + +/** Request and response helpers shared by every dashboard route (M16-T01). */ + +const MAX_BODY_BYTES = 2 * 1024 * 1024; + +const MIME_TYPES = Object.freeze({ + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', +}); + +/** + * Sent on every response. The dashboard ships no third-party asset, so the policy + * can stay restricted to `self` without breaking anything. + */ +const SECURITY_HEADERS = Object.freeze({ + 'X-Content-Type-Options': 'nosniff', + 'X-Frame-Options': 'DENY', + 'Referrer-Policy': 'same-origin', + 'Content-Security-Policy': + "default-src 'self'; img-src 'self' data: https://cdn.discordapp.com; " + + "style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; " + + "frame-ancestors 'none'; base-uri 'none'; form-action 'self'", +}); + +export class HttpError extends Error { + constructor(status, message, details = null) { + super(message); + this.name = 'HttpError'; + this.status = status; + this.details = details; + } +} + +export const badRequest = (message, details) => new HttpError(400, message, details); +export const unauthorized = (message = 'Authentification requise') => new HttpError(401, message); +export const forbidden = (message = 'Accès refusé') => new HttpError(403, message); +export const notFound = (message = 'Ressource introuvable') => new HttpError(404, message); + +export function sendJson(response, status, payload) { + const body = JSON.stringify(payload ?? null); + response.writeHead(status, { + ...SECURITY_HEADERS, + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(body), + 'Cache-Control': 'no-store', + }); + 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 = {}) { + response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end(); +} + +export function redirect(response, location, headers = {}) { + sendEmpty(response, 302, { ...headers, Location: location }); +} + +export function readRawBody(request, limit = MAX_BODY_BYTES) { + return new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > limit) { + reject(new HttpError(413, 'Corps de requête trop volumineux')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks))); + request.on('error', reject); + }); +} + +export async function readJsonBody(request) { + const raw = await readRawBody(request); + if (raw.length === 0) return {}; + try { + const parsed = JSON.parse(raw.toString('utf8')); + if (parsed === null || typeof parsed !== 'object') throw new Error('not an object'); + return parsed; + } catch { + throw badRequest('Corps JSON invalide'); + } +} + +export function parseCookies(header = '') { + const jar = {}; + for (const part of header.split(';')) { + const index = part.indexOf('='); + if (index < 0) continue; + jar[part.slice(0, index).trim()] = decodeURIComponent(part.slice(index + 1).trim()); + } + return jar; +} + +export function serializeCookie(name, value, { maxAge, secure = false, path: cookiePath = '/' } = {}) { + const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${cookiePath}`, 'HttpOnly', 'SameSite=Lax']; + if (secure) parts.push('Secure'); + if (maxAge !== undefined) parts.push(`Max-Age=${Math.floor(maxAge)}`); + return parts.join('; '); +} + +/** Appends a cookie without dropping the ones already queued on the response. */ +export function appendCookie(response, cookie) { + const existing = response.getHeader('Set-Cookie'); + const list = existing ? [].concat(existing) : []; + response.setHeader('Set-Cookie', [...list, cookie]); +} + +/** Client address, trusting `X-Forwarded-For` only for its left-most entry. */ +export function clientIp(request) { + const forwarded = request.headers['x-forwarded-for']; + if (typeof forwarded === 'string' && forwarded.length > 0) return forwarded.split(',')[0].trim(); + return request.socket.remoteAddress ?? ''; +} + +/** + * Serves a file from `root`, refusing anything that escapes it. + * Returns false when the file does not exist, so the caller can fall back. + */ +export async function sendStatic(response, root, requestPath, { fallback = null, request = null } = {}) { + const relative = decodeURIComponent(requestPath).replace(/^\/+/, ''); + const resolved = path.resolve(root, relative || 'index.html'); + const target = resolved.startsWith(path.resolve(root)) ? resolved : null; + + let file = target; + if (file) { + const info = await stat(file).catch(() => null); + if (info?.isDirectory()) file = path.join(file, 'index.html'); + else if (!info?.isFile()) file = null; + } + if (!file && fallback) file = path.resolve(root, fallback); + if (!file) return false; + + const info = await stat(file).catch(() => null); + if (!info?.isFile()) return false; + + 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, { + ...SECURITY_HEADERS, + 'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream', + 'Content-Length': info.size, + // Every module is fetched fresh rather than revalidated. + // + // 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); + return true; +} diff --git a/src/web/public/app.js b/src/web/public/app.js new file mode 100644 index 0000000..e98fa92 --- /dev/null +++ b/src/web/public/app.js @@ -0,0 +1,449 @@ +import { api } from './core/api.js'; +import { h, mount, qs } from './core/dom.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'; + +/** Shell, navigation and hash routing of the dashboard (M16-T11). */ + +const LEVELS = { USER: 0, STAFF: 1, DEV: 2, OWNER: 3 }; + +/** + * `module` is imported on demand, so a view is only downloaded when visited. + * `level` hides a page the visitor could not use anyway; the server enforces it too. + */ +const ROUTES = [ + { + path: '', + icon: '◎', + label: 'Vue d’ensemble', + group: 'Pilotage', + module: './views/overview.js', + level: LEVELS.STAFF, + }, + { + path: 'tasks', + icon: '✓', + label: 'Mes tâches', + group: 'Pilotage', + module: './views/tasks.js', + level: LEVELS.STAFF, + }, + { + path: 'org', + icon: '⬡', + label: 'Organisation', + group: 'Pilotage', + module: './views/organization.js', + level: LEVELS.STAFF, + }, + { + path: 'projects', + icon: '▦', + label: 'Projets', + group: 'Pilotage', + module: './views/projects.js', + level: LEVELS.STAFF, + }, + { + path: 'repos', + icon: '◫', + label: 'Dépôts', + group: 'Code', + module: './views/repositories.js', + level: LEVELS.STAFF, + }, + { + path: 'releases', + icon: '⬀', + label: 'Releases', + group: 'Code', + module: './views/releases.js', + level: LEVELS.STAFF, + }, + { + path: 'deploy', + icon: '⚙', + label: 'Déploiements', + group: 'Code', + module: './views/deployments.js', + level: LEVELS.STAFF, + }, + { + path: 'discord', + icon: '☰', + label: 'Serveur Discord', + group: 'Communauté', + module: './views/discord.js', + level: LEVELS.STAFF, + }, + { + path: 'community', + icon: '✦', + label: 'Tickets & vocaux', + group: 'Communauté', + module: './views/community.js', + level: LEVELS.STAFF, + }, + { + path: 'wiki', + icon: '📖', + label: 'Wiki', + group: 'Communauté', + module: './views/wiki.js', + level: LEVELS.STAFF, + }, + { + path: 'logs', + icon: '≡', + label: 'Journaux', + group: 'Système', + module: './views/logs.js', + level: LEVELS.STAFF, + advanced: true, + }, + { + path: 'settings', + icon: '⚒', + label: 'Paramètres', + group: 'Système', + module: './views/settings.js', + level: LEVELS.STAFF, + }, + { + path: 'setup', + icon: '✎', + label: 'Configuration .env', + group: 'Système', + module: './views/setup.js', + level: LEVELS.OWNER, + }, +]; + +export const state = { + me: null, + config: null, + mode: localStorage.getItem('fws.mode') ?? 'simple', + theme: localStorage.getItem('fws.theme') ?? 'dark', + /** Repository selected in the Releases and Deployments pages. */ + repository: localStorage.getItem('fws.repository') ?? '', +}; + +export function setMode(mode) { + state.mode = mode; + localStorage.setItem('fws.mode', mode); + document.body.dataset.mode = mode; + render(); +} + +export function setTheme(theme) { + state.theme = theme; + localStorage.setItem('fws.theme', theme); + document.documentElement.dataset.theme = theme; +} + +export function setRepository(fullName) { + state.repository = fullName; + localStorage.setItem('fws.repository', fullName); +} + +export const navigate = (path) => { + window.location.hash = `#/${path}`; +}; + +const currentRoute = () => { + const raw = window.location.hash.replace(/^#\/?/, ''); + const [path] = raw.split('?'); + const segments = path.split('/').filter(Boolean); + return { segments, path, active: activePath(window.location.hash) }; +}; + +/** + * Marks the current entry in the sidebar and retitles the tab. + * + * Navigation only swaps the main area, so the highlight has to be refreshed on + * its own — otherwise it keeps pointing at the page you arrived on. + */ +function highlightNav(scope = document) { + const active = highlight(scope, window.location.hash); + const route = ROUTES.find((entry) => entry.path === active); + document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; +} + +const LIVE_LABELS = { + live: 'À jour en direct', + connecting: 'Connexion…', + reconnecting: 'Reconnexion…', + polling: 'Rafraîchissement périodique', + paused: 'En pause (onglet en arrière-plan)', + idle: 'Hors ligne', +}; + +let stopWatchingStatus = null; + +/** Small footer badge: says whether the page is following the bot live. */ +function liveIndicator() { + const dot = h('span', { class: 'live-dot' }); + const label = h('span', { text: LIVE_LABELS.idle }); + const node = h('div', { class: 'live', title: 'État de la mise à jour automatique' }, dot, label); + + stopWatchingStatus?.(); + stopWatchingStatus = onStatus(({ status, lastEventAt }) => { + node.dataset.status = status; + label.textContent = LIVE_LABELS[status] ?? status; + if (lastEventAt) { + node.title = `Dernière mise à jour à ${lastEventAt.toLocaleTimeString('fr-FR')}`; + } + }); + return node; +} + +/** + * Pages the visitor can actually reach. Shared with the palette so a search + * 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 = []; + for (const route of visible) { + let group = groups.find((entry) => entry.name === route.group); + if (!group) groups.push((group = { name: route.group, routes: [] })); + group.routes.push(route); + } + + return h( + 'aside', + { class: 'sidebar' }, + h( + 'a', + { class: 'brand', href: '#/' }, + h('img', { src: 'favicon.svg', alt: '' }), + 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( + 'nav', + { class: 'nav' }, + groups.map((group) => [ + h('div', { class: 'nav-group', text: group.name }), + group.routes.map((route) => + h( + 'a', + { href: `#/${route.path}`, dataset: { route: route.path } }, + h('span', { class: 'nav-icon', text: route.icon }), + 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 }), + ), + ), + ]), + ), + h( + 'div', + { class: 'sidebar-foot' }, + h( + 'div', + { class: 'mode-switch', role: 'group', 'aria-label': 'Mode d’affichage' }, + button('Simple', () => setMode('simple'), {}), + button('Avancé', () => setMode('advanced'), {}), + ), + liveIndicator(), + h('div', { class: 'build muted', text: '…' }), + h( + 'div', + { class: 'viewer' }, + state.me.avatar && h('img', { src: state.me.avatar, alt: '' }), + h( + 'div', + {}, + h('strong', { text: state.me.displayName ?? state.me.username ?? 'Invité' }), + h('span', { class: 'muted', text: ACCESS_LABELS[state.me.accessLevel] ?? '—' }), + ), + ), + h( + 'div', + { class: 'row' }, + button( + state.theme === 'dark' ? '☀ Clair' : '☾ Sombre', + () => { + setTheme(state.theme === 'dark' ? 'light' : 'dark'); + render(); + }, + { tone: 'ghost' }, + ), + button( + 'Déconnexion', + async () => { + await api.post('/api/auth/logout'); + window.location.reload(); + }, + { tone: 'ghost' }, + ), + ), + ), + ); +} + +function applyModeButtons(node) { + for (const control of node.querySelectorAll('.mode-switch button')) { + control.classList.toggle( + 'active', + control.textContent === (state.mode === 'simple' ? 'Simple' : 'Avancé'), + ); + } +} + +async function renderView(host) { + const { segments } = currentRoute(); + const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); + resetSubscriptions(); + highlightNav(); + refreshTaskCount(); + host.scrollIntoView?.({ block: 'start' }); + + if (!route) { + mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' }))); + return; + } + if (state.me.accessLevel < route.level) { + mount( + host, + h( + 'div', + { class: 'notice notice-error' }, + h('p', { text: 'Cette page demande un niveau d’accès supérieur.' }), + ), + ); + return; + } + + mount(host, spinner()); + try { + const module = await import(route.module); + await module.render(host, { params: segments.slice(1), state }); + } catch (error) { + console.error('[fws] échec de la vue', error); + const { errorBox } = await import('./core/ui.js'); + mount(host, errorBox(error.message, { retry: () => renderView(host), error })); + } +} + +export function render() { + const app = qs('#app'); + + if (!state.me?.authenticated) { + import('./views/login.js').then((module) => module.render(app, { state })); + return; + } + + // The bootstrap session may only reach the wizard, so it never gets a shell. + if (state.me.source === 'setup') { + import('./views/setup.js').then((module) => module.render(app, { state, standalone: true })); + return; + } + + const main = h('main', { class: 'main' }); + const shell = h('div', { class: 'shell' }, sidebar(), main); + mount(app, shell); + applyModeButtons(shell); + highlightNav(shell); + refreshTaskCount(); + 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. */ +async function showBuild() { + const health = await api.get('/api/health').catch(() => null); + const node = qs('.build'); + if (!node || !health) return; + + const built = health.buildAt + ? new Date(health.buildAt).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' }) + : 'date inconnue'; + node.textContent = `v${health.version} · interface du ${built}`; + node.title = "Date du fichier d'interface le plus récent servi par le bot."; +} + +async function boot() { + document.body.dataset.mode = state.mode; + document.documentElement.dataset.theme = state.theme; + + const [me, config] = await Promise.all([ + api.get('/api/me').catch(() => ({ authenticated: false })), + api.get('/api/auth/config').catch(() => ({})), + ]); + state.me = me; + state.config = config; + + startLive(); + showBuild(); + bindPalette(visibleRoutes); + + window.addEventListener('hashchange', () => { + const main = qs('.main'); + // Without the shell in place there is nothing to swap, so rebuild the page. + if (main && state.me?.authenticated && state.me.source !== 'setup') renderView(main); + else render(); + }); + window.addEventListener('unhandledrejection', (event) => { + if (event.reason?.status === 401) { + state.me = { authenticated: false }; + render(); + } else if (event.reason instanceof Error) toast(event.reason.message, 'error'); + }); + + render(); +} + +boot(); diff --git a/src/web/public/core/api.js b/src/web/public/core/api.js new file mode 100644 index 0000000..481bce0 --- /dev/null +++ b/src/web/public/core/api.js @@ -0,0 +1,51 @@ +/** Typed-ish client for the dashboard API (M16-T11). */ + +export class ApiError extends Error { + constructor(status, message, details) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.details = details; + } +} + +async function request(method, path, body) { + const response = await fetch(path, { + method, + headers: { + Accept: 'application/json', + ...(body !== undefined && { 'Content-Type': 'application/json' }), + // Required by the server for every write: a cross-site form cannot set it. + 'X-Requested-With': 'fws-dashboard', + }, + body: body === undefined ? undefined : JSON.stringify(body), + credentials: 'same-origin', + }); + + const payload = await response.json().catch(() => null); + if (!response.ok) { + throw new ApiError(response.status, payload?.error ?? `Erreur ${response.status}`, payload?.details); + } + return payload; +} + +const withQuery = (path, params) => { + const search = new URLSearchParams( + Object.entries(params ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== ''), + ).toString(); + return search ? `${path}?${search}` : path; +}; + +export const api = { + get: (path, params) => request('GET', withQuery(path, params)), + post: (path, body = {}) => request('POST', path, body), + put: (path, body = {}) => request('PUT', path, body), + patch: (path, body = {}) => request('PATCH', path, body), + delete: (path, body = {}) => request('DELETE', path, body), +}; + +export const encodeRepo = (fullName) => + String(fullName) + .split('/') + .map((part) => encodeURIComponent(part)) + .join('/'); diff --git a/src/web/public/core/dom.js b/src/web/public/core/dom.js new file mode 100644 index 0000000..6da3287 --- /dev/null +++ b/src/web/public/core/dom.js @@ -0,0 +1,122 @@ +/** + * Minimal DOM helpers. No framework, no build step: the dashboard ships the + * files it serves (M16-T11). + */ + +/** + * `h('div', { class: 'card' }, h('h2', { text: 'Titre' }))` + * Text always goes through `textContent`, so API values can never inject markup. + */ +export function h(tag, props = {}, ...children) { + const node = document.createElement(tag); + + for (const [key, value] of Object.entries(props ?? {})) { + if (value === null || value === undefined || value === false) continue; + + if (key === 'text') node.textContent = String(value); + else if (key === 'class') node.className = value; + else if (key === 'dataset') Object.assign(node.dataset, value); + else if (key === 'style') Object.assign(node.style, value); + else if (key.startsWith('on') && typeof value === 'function') { + node.addEventListener(key.slice(2).toLowerCase(), value); + } else if (key === 'value' || key === 'checked' || key === 'disabled' || key === 'selected') { + node[key] = value; + } else node.setAttribute(key, value === true ? '' : String(value)); + } + + for (const child of children.flat(Infinity)) { + if (child === null || child === undefined || child === false) continue; + node.append(child instanceof Node ? child : document.createTextNode(String(child))); + } + return node; +} + +export const clear = (node) => { + while (node.firstChild) node.firstChild.remove(); + return node; +}; + +export const mount = (node, ...children) => { + clear(node); + node.append(...children.flat(Infinity).filter(Boolean)); + return node; +}; + +export const qs = (selector, scope = document) => scope.querySelector(selector); + +/** Escapes then applies the small subset of Markdown used by Gitea bodies. */ +export function markdown(text) { + const escaped = String(text ?? '') + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>'); + + return escaped + .replace(/```([\s\S]*?)```/g, (_, code) => `
${code.trim()}
`) + .replace(/`([^`\n]+)`/g, '$1') + .replace(/^### (.+)$/gm, '

$1

') + .replace(/^## (.+)$/gm, '

$1

') + .replace(/^# (.+)$/gm, '

$1

') + .replace(/\*\*([^*\n]+)\*\*/g, '$1') + .replace(/^[-*] (.+)$/gm, '
  • $1
  • ') + .replace(/(
  • [\s\S]*?<\/li>)/g, '
      $1
    ') + .replace(/\n{2,}/g, '

    '); +} + +/** Renders trusted Markdown built above; never call it with raw HTML. */ +export function richText(text, className = 'rich') { + const node = h('div', { class: className }); + node.innerHTML = markdown(text); + return node; +} + +export const formatDate = (value) => { + if (!value) return '—'; + const date = new Date(String(value).includes('T') ? value : `${value}Z`); + if (Number.isNaN(date.getTime())) return String(value); + return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' }); +}; + +export function formatRelative(value) { + if (!value) return '—'; + const date = new Date(String(value).includes('T') ? value : `${value}Z`); + if (Number.isNaN(date.getTime())) return String(value); + + const seconds = Math.round((date.getTime() - Date.now()) / 1000); + const units = [ + ['year', 31_536_000], + ['month', 2_592_000], + ['day', 86_400], + ['hour', 3600], + ['minute', 60], + ]; + const formatter = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' }); + + for (const [unit, size] of units) { + if (Math.abs(seconds) >= size) return formatter.format(Math.round(seconds / size), unit); + } + return formatter.format(seconds, 'second'); +} + +export const formatBytes = (bytes) => { + const value = Number(bytes) || 0; + const units = ['o', 'Ko', 'Mo', 'Go']; + let index = 0; + let result = value; + while (result >= 1024 && index < units.length - 1) { + result /= 1024; + index += 1; + } + return `${result.toFixed(index === 0 ? 0 : 1)} ${units[index]}`; +}; + +export const formatDuration = (ms) => { + const seconds = Math.floor(Number(ms) / 1000); + 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`; +}; diff --git a/src/web/public/core/live.js b/src/web/public/core/live.js new file mode 100644 index 0000000..054e488 --- /dev/null +++ b/src/web/public/core/live.js @@ -0,0 +1,169 @@ +/** + * Live updates (M16-T12). + * + * One `EventSource` for the whole dashboard; views declare what they want to + * hear and get called back. When the stream cannot be established — a proxy + * that buffers, a network that drops it — a timer takes over so the pages still + * refresh, just less promptly. + */ + +/** + * A single slot rather than a list: exactly one view is on screen, and a view + * that re-renders itself on refresh would otherwise register a second listener + * each time, doubling the work on every event. + */ +let viewRefresher = null; +const STATUS_LISTENERS = new Set(); +const FALLBACK_MS = 30_000; +/** Backoff between reconnection attempts, capped so it always keeps trying. */ +const RETRY_MS = [2000, 5000, 15_000, 30_000]; + +let source = null; +let fallbackTimer = null; +let attempts = 0; +let status = 'idle'; +let lastEventAt = null; + +function setStatus(next) { + if (status === next) return; + status = next; + for (const listener of STATUS_LISTENERS) listener({ status, lastEventAt }); +} + +function emit(event) { + lastEventAt = new Date(); + try { + viewRefresher?.(event); + } catch { + // A failing view must not take the stream down with it. + } + setStatus(fallbackTimer ? 'polling' : 'live'); +} + +function startFallback() { + if (fallbackTimer) return; + fallbackTimer = setInterval(() => emit({ topic: 'tick', fallback: true }), FALLBACK_MS); + setStatus('polling'); +} + +function stopFallback() { + clearInterval(fallbackTimer); + fallbackTimer = null; +} + +function connect() { + if (source || document.hidden) return; + + setStatus(attempts === 0 ? 'connecting' : 'reconnecting'); + source = new EventSource('/api/events', { withCredentials: true }); + + source.addEventListener('open', () => { + attempts = 0; + stopFallback(); + setStatus('live'); + }); + + for (const topic of [ + 'ready', + 'tick', + 'mutation', + 'deployments', + 'gitea', + 'discord', + 'community', + 'projects', + 'settings', + ]) { + source.addEventListener(topic, (event) => { + let payload = { topic }; + try { + payload = { ...JSON.parse(event.data), topic }; + } catch { + // A frame we cannot read is still a signal that something moved. + } + emit(payload); + }); + } + + source.addEventListener('error', () => { + source?.close(); + source = null; + + // The browser reconnects on its own, but only while the page stays open and + // the server keeps answering; the timer covers the rest. + startFallback(); + const delay = RETRY_MS[Math.min(attempts, RETRY_MS.length - 1)]; + attempts += 1; + setTimeout(connect, delay); + }); +} + +/** Stops the stream while the tab is in the background, resumes on return. */ +document.addEventListener('visibilitychange', () => { + if (document.hidden) { + source?.close(); + source = null; + stopFallback(); + setStatus('paused'); + } else { + connect(); + // Coming back to the tab, the page is stale by definition. + emit({ topic: 'tick', resumed: true }); + } +}); + +export function startLive() { + connect(); +} + +export function onStatus(listener) { + STATUS_LISTENERS.add(listener); + listener({ status, lastEventAt }); + return () => STATUS_LISTENERS.delete(listener); +} + +export const liveStatus = () => ({ status, lastEventAt }); + +/** Drops the current view subscription, called when navigating elsewhere. */ +export function resetSubscriptions() { + viewRefresher = null; +} + +/** + * Re-runs `refresh` when a relevant event arrives. + * + * Refreshing under someone's fingers is worse than showing slightly old data, + * so a refresh is skipped while a dialog is open or a field has focus, and + * replayed once the way is clear. + */ +export function autoRefresh(refresh, { topics = ['tick'], minIntervalMs = 5000 } = {}) { + const wanted = new Set(topics); + let lastRun = Date.now(); + let pending = false; + + const busy = () => + document.querySelector('.overlay') !== null || + ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName); + + const run = () => { + if (busy()) { + pending = true; + return; + } + pending = false; + lastRun = Date.now(); + refresh(); + }; + + const listener = (event) => { + if (!wanted.has(event.topic) && !pending) return; + // A burst of writes must not turn into a burst of reloads. + if (Date.now() - lastRun < minIntervalMs && !pending) return; + run(); + }; + + viewRefresher = listener; + return () => { + if (viewRefresher === listener) viewRefresher = null; + }; +} diff --git a/src/web/public/core/markdown.js b/src/web/public/core/markdown.js new file mode 100644 index 0000000..3b9d9d5 --- /dev/null +++ b/src/web/public/core/markdown.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +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, '$1') + .replace( + /!\[([^\]]*)\]\(([^)\s]+)\)/g, + (_, alt, src) => `${alt}`, + ) + .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 `${label}`; + }) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2') + .replace(/~~([^~]+)~~/g, '$1'); +} + +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(``); + }; + 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(`
    ${body.join('\n')}
    `); + 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( + `
    ${header + .map((cell) => ``) + .join('')}${rows + .map((row) => `${row.map((cell) => ``).join('')}`) + .join('')}
    ${cell}
    ${cell}
    `, + ); + 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(`${inline(text)}`); + index += 1; + continue; + } + + if (/^\s*(---|\*\*\*)\s*$/.test(line)) { + closeList(listStack); + out.push('
    '); + index += 1; + continue; + } + + const quote = /^>\s?(.*)$/.exec(line); + if (quote) { + closeList(listStack); + const body = [quote[1]]; + index += 1; + while (index < lines.length && /^>\s?/.test(lines[index])) { + body.push(lines[index++].replace(/^>\s?/, '')); + } + out.push(`
    ${inline(body.join(' '))}
    `); + 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(`
  • ${inline((bullet ?? ordered)[1])}
  • `); + 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|>|```)/.test(lines[index]) && + !lines[index].includes('|') + ) { + paragraph.push(lines[index++]); + } + out.push(`

    ${inline(paragraph.join(' '))}

    `); + } + + closeList(listStack); + return { html: out.join('\n'), headings }; +} diff --git a/src/web/public/core/nav.js b/src/web/public/core/nav.js new file mode 100644 index 0000000..936a995 --- /dev/null +++ b/src/web/public/core/nav.js @@ -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; +} diff --git a/src/web/public/core/palette.js b/src/web/public/core/palette.js new file mode 100644 index 0000000..b11b0b8 --- /dev/null +++ b/src/web/public/core/palette.js @@ -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()); + }); +} diff --git a/src/web/public/core/ui.js b/src/web/public/core/ui.js new file mode 100644 index 0000000..0506aaa --- /dev/null +++ b/src/web/public/core/ui.js @@ -0,0 +1,282 @@ +import { clear, h, mount } from './dom.js'; + +/** Shared widgets: cards, tables, badges, toasts, modals (M16-T11). */ + +export const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' }; + +export function card(title, { subtitle, actions, advanced = false } = {}, ...children) { + return h( + 'section', + { class: advanced ? 'card advanced-only' : 'card' }, + (title || actions) && + h( + 'header', + { class: 'card-head' }, + h( + 'div', + {}, + title && h('h2', { text: title }), + subtitle && h('p', { class: 'muted', text: subtitle }), + ), + actions && h('div', { class: 'card-actions' }, actions), + ), + h('div', { class: 'card-body' }, ...children), + ); +} + +export const stat = (label, value, { hint, tone = 'neutral' } = {}) => + h( + 'div', + { class: `stat stat-${tone}` }, + h('span', { class: 'stat-label', text: label }), + h('strong', { class: 'stat-value', text: value ?? '—' }), + hint && h('span', { class: 'stat-hint', text: hint }), + ); + +export const badge = (text, tone = 'neutral') => h('span', { class: `badge badge-${tone}`, text }); + +export const button = (label, onClick, { tone = 'ghost', disabled = false, title, type = 'button' } = {}) => + h('button', { class: `btn btn-${tone}`, onClick, disabled, title, type, text: label }); + +export function field(label, control, { help, error } = {}) { + return h( + 'label', + { class: error ? 'field field-error' : 'field' }, + h('span', { class: 'field-label', text: label }), + control, + help && h('span', { class: 'field-help', text: help }), + error && h('span', { class: 'field-error-text', text: error }), + ); +} + +export const input = (props = {}) => h('input', { class: 'input', ...props }); +export const textarea = (props = {}) => h('textarea', { class: 'input textarea', ...props }); + +export function select(options, props = {}) { + return h( + 'select', + { class: 'input', ...props }, + options.map((option) => + h('option', { + value: option.value, + text: option.label, + selected: option.value === props.value, + }), + ), + ); +} + +export function toggle(checked, onChange, label) { + return h( + 'label', + { class: 'toggle' }, + h('input', { type: 'checkbox', checked, onChange: (event) => onChange(event.target.checked) }), + h('span', { class: 'toggle-track' }), + label && h('span', { text: label }), + ); +} + +/** + * Renders a table. Each column is `{ key, label, render?, className? }`; + * `render` returns a Node or a string. + */ +export function table(columns, rows, { empty = 'Rien à afficher pour le moment.', rowHref = null } = {}) { + if (!rows || rows.length === 0) { + // An empty state is where people look for the action that fills it, so it + // accepts a node and not only a sentence. + return empty instanceof Node + ? h('div', { class: 'empty' }, empty) + : h('p', { class: 'empty', text: empty }); + } + + return h( + 'div', + { class: 'table-wrap' }, + h( + 'table', + { class: 'table' }, + h( + 'thead', + {}, + h( + 'tr', + {}, + columns.map((column) => h('th', { class: column.className ?? '', text: column.label })), + ), + ), + h( + 'tbody', + {}, + rows.map((row) => { + const target = rowHref?.(row) ?? null; + const line = h( + 'tr', + target ? { class: 'row-link', tabindex: '0', role: 'link' } : {}, + columns.map((column) => { + const cell = h('td', { class: column.className ?? '' }); + const value = column.render ? column.render(row) : row[column.key]; + if (value instanceof Node) cell.append(value); + else cell.textContent = value === null || value === undefined ? '—' : String(value); + 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; + }), + ), + ), + ); +} + +export const spinner = (label = 'Chargement…') => + h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label })); + +/** + * 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( + 'div', + { class: 'notice notice-error' }, + 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' }), + ); + +export const notice = (message, tone = 'info') => + h('div', { class: `notice notice-${tone}` }, h('p', { text: message })); + +let toastHost; + +export function toast(message, tone = 'success') { + toastHost ??= document.body.appendChild(h('div', { class: 'toast-host' })); + const node = h('div', { class: `toast toast-${tone}`, text: message }); + toastHost.append(node); + setTimeout(() => node.classList.add('toast-out'), 3600); + setTimeout(() => node.remove(), 4200); +} + +/** Promise-based modal. Resolves with the value passed to `close`. */ +export function modal(title, buildBody, { confirmLabel = 'Confirmer', tone = 'primary' } = {}) { + return new Promise((resolve) => { + const overlay = h('div', { class: 'overlay' }); + const close = (value) => { + overlay.remove(); + document.removeEventListener('keydown', onKey); + resolve(value); + }; + const onKey = (event) => { + if (event.key === 'Escape') close(null); + }; + + const body = buildBody(close); + const footer = h( + 'footer', + { class: 'modal-foot' }, + button('Annuler', () => close(null), { tone: 'ghost' }), + button(confirmLabel, () => close(body.submit ? body.submit() : true), { tone }), + ); + + overlay.append( + h( + 'div', + { class: 'modal' }, + h('header', { class: 'modal-head' }, h('h2', { text: title })), + h('div', { class: 'modal-body' }, body.node ?? body), + footer, + ), + ); + overlay.addEventListener('click', (event) => { + if (event.target === overlay) close(null); + }); + document.addEventListener('keydown', onKey); + document.body.append(overlay); + + const firstInput = overlay.querySelector('input, textarea, select'); + firstInput?.focus(); + }); +} + +/** Confirmation that requires typing an exact phrase, for irreversible actions. */ +export function confirmDangerous(title, message, phrase) { + return modal( + title, + () => { + const control = input({ placeholder: phrase, autocomplete: 'off' }); + const node = h( + 'div', + {}, + h('p', { text: message }), + h('p', { class: 'muted', text: `Tape « ${phrase} » pour confirmer.` }), + control, + ); + return { node, submit: () => control.value.trim() === phrase }; + }, + { confirmLabel: 'Supprimer', tone: 'danger' }, + ); +} + +export const confirmAction = (title, message) => + modal(title, () => ({ node: h('p', { text: message }), submit: () => true })); + +/** + * Renders an async view into a host node, showing a loader then the result. + * Any thrown error becomes a retry box instead of a blank page. + */ +export async function renderAsync(host, load, build) { + mount(host, spinner()); + try { + const data = await load(); + mount(host, await build(data)); + } catch (error) { + // 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; +} + +export const section = (...children) => h('div', { class: 'stack' }, ...children); +export const row = (...children) => h('div', { class: 'row' }, ...children); +export const grid = (...children) => h('div', { class: 'grid' }, ...children); +export { clear, mount }; diff --git a/src/web/public/favicon.svg b/src/web/public/favicon.svg new file mode 100644 index 0000000..972855a --- /dev/null +++ b/src/web/public/favicon.svg @@ -0,0 +1,29 @@ + + FWS Linux + + + + + FWS + + + Linux + + diff --git a/src/web/public/index.html b/src/web/public/index.html new file mode 100644 index 0000000..e98b2dc --- /dev/null +++ b/src/web/public/index.html @@ -0,0 +1,18 @@ + + + + + + + + FWS-Bot — Tableau de bord + + + + +
    + +
    + + + diff --git a/src/web/public/styles.css b/src/web/public/styles.css new file mode 100644 index 0000000..451f188 --- /dev/null +++ b/src/web/public/styles.css @@ -0,0 +1,1532 @@ +/* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */ + +:root { + /* Official FWS mark: cyan ring on dark navy. */ + --blue: #22d3ee; + --blue-soft: #7fe7f8; + --green: #2ecc71; + --amber: #f1c40f; + --red: #e74c3c; + --violet: #9b59b6; + --gitea: #609926; + + --bg: #10141f; + --bg-elevated: #171c2b; + --bg-sunken: #0c1018; + --surface: #1b2130; + --border: #2a3145; + --text: #e6ebf3; + --text-muted: #8f98ad; + --shadow: 0 10px 30px rgb(0 0 0 / 35%); + + --radius: 12px; + --radius-sm: 8px; + --sidebar: 250px; + --font: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif; + --mono: ui-monospace, 'JetBrains Mono', 'Fira Code', Menlo, Consolas, monospace; +} + +[data-theme='light'] { + --bg: #f4f7fa; + --bg-elevated: #ffffff; + --bg-sunken: #e8eef5; + --surface: #ffffff; + --border: #d5e0ea; + --text: #14212e; + --text-muted: #5b6e80; + --shadow: 0 8px 24px rgb(20 33 46 / 10%); +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + height: 100%; +} + +body { + background: var(--bg); + color: var(--text); + font-family: var(--font); + font-size: 15px; + line-height: 1.55; + -webkit-font-smoothing: antialiased; +} + +a { + color: var(--blue-soft); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +h1, +h2, +h3, +h4 { + margin: 0; + line-height: 1.25; + font-weight: 650; +} +h1 { + font-size: 1.5rem; +} +h2 { + font-size: 1.05rem; +} +h3 { + font-size: 0.95rem; +} + +p { + margin: 0 0 0.6rem; +} +p:last-child { + margin-bottom: 0; +} + +code, +pre { + font-family: var(--mono); + font-size: 0.85em; +} +code { + background: var(--bg-sunken); + border-radius: 4px; + padding: 0.1em 0.35em; +} +pre { + background: var(--bg-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.8rem; + overflow: auto; + max-height: 400px; +} +pre code { + background: none; + padding: 0; +} + +.muted { + color: var(--text-muted); + font-size: 0.88rem; +} + +/* --- Layout ------------------------------------------------------------- */ + +.app { + min-height: 100%; +} + +.shell { + display: grid; + grid-template-columns: var(--sidebar) 1fr; + min-height: 100vh; +} + +.sidebar { + background: var(--bg-elevated); + border-right: 1px solid var(--border); + padding: 1.1rem 0.9rem; + display: flex; + flex-direction: column; + gap: 1.2rem; + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; +} + +.brand { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0 0.4rem; +} +.brand img { + width: 34px; + height: 34px; + border-radius: 9px; +} +.brand strong { + display: block; + font-size: 0.98rem; +} +.brand span { + display: block; + color: var(--text-muted); + font-size: 0.75rem; +} + +.nav { + display: flex; + flex-direction: column; + gap: 0.15rem; +} +.nav-group { + margin-top: 0.7rem; + padding: 0 0.6rem 0.25rem; + font-size: 0.68rem; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--text-muted); +} +.nav a { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.65rem; + border-radius: var(--radius-sm); + color: var(--text); + font-size: 0.9rem; +} +.nav a:hover { + background: var(--surface); + text-decoration: none; +} +.nav a.active { + background: color-mix(in srgb, var(--blue) 18%, transparent); + color: var(--blue-soft); + font-weight: 600; + /* Inset rather than a border: a real border would shift the label. */ + box-shadow: inset 3px 0 0 var(--blue); +} +.nav a.active .nav-icon { + opacity: 1; +} +.nav-icon { + width: 1.15rem; + text-align: center; + opacity: 0.85; +} + +.sidebar-foot { + margin-top: auto; + display: flex; + flex-direction: column; + gap: 0.6rem; + font-size: 0.8rem; +} + +.viewer { + display: flex; + align-items: center; + gap: 0.55rem; + padding: 0.5rem; + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.viewer img { + width: 30px; + height: 30px; + border-radius: 50%; +} +.viewer div { + min-width: 0; +} +.viewer strong { + display: block; + font-size: 0.85rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.main { + padding: 1.4rem 1.8rem 3rem; + min-width: 0; +} + +.page-head { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1.2rem; +} + +.stack { + display: flex; + flex-direction: column; + gap: 1rem; +} +.row { + display: flex; + flex-wrap: wrap; + gap: 0.6rem; + align-items: center; +} +.grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); + gap: 0.9rem; +} + +/* --- Components ---------------------------------------------------------- */ + +.card { + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; +} +.card-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + padding: 0.85rem 1.1rem; + border-bottom: 1px solid var(--border); +} +.card-actions { + display: flex; + gap: 0.45rem; + flex-wrap: wrap; +} +.card-body { + padding: 1.1rem; + display: flex; + flex-direction: column; + gap: 0.9rem; +} + +.stat { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.75rem 0.9rem; + display: flex; + flex-direction: column; + gap: 0.1rem; +} +.stat-label { + font-size: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-muted); +} +.stat-value { + font-size: 1.45rem; + line-height: 1.2; +} +.stat-hint { + font-size: 0.78rem; + color: var(--text-muted); +} +.stat-success .stat-value { + color: var(--green); +} +.stat-warning .stat-value { + color: var(--amber); +} +.stat-danger .stat-value { + color: var(--red); +} +.stat-primary .stat-value { + color: var(--blue-soft); +} + +.badge { + display: inline-flex; + align-items: center; + gap: 0.3rem; + padding: 0.12rem 0.5rem; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 600; + border: 1px solid transparent; + white-space: nowrap; +} +.badge-neutral { + background: var(--surface); + color: var(--text-muted); + border-color: var(--border); +} +.badge-success { + background: color-mix(in srgb, var(--green) 18%, transparent); + color: var(--green); +} +.badge-warning { + background: color-mix(in srgb, var(--amber) 18%, transparent); + color: var(--amber); +} +.badge-danger { + background: color-mix(in srgb, var(--red) 18%, transparent); + color: var(--red); +} +.badge-info { + background: color-mix(in srgb, var(--blue) 20%, transparent); + color: var(--blue-soft); +} +.badge-gitea { + background: color-mix(in srgb, var(--gitea) 22%, transparent); + color: #a8d96a; +} + +.btn { + font: inherit; + font-size: 0.86rem; + font-weight: 600; + padding: 0.42rem 0.8rem; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + cursor: pointer; + transition: + background 0.12s ease, + border-color 0.12s ease; +} +.btn:hover:not(:disabled) { + border-color: var(--blue); +} +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.btn-primary { + background: var(--blue); + border-color: var(--blue); + color: #0c1018; +} +.btn-primary:hover:not(:disabled) { + filter: brightness(1.1); +} +.btn-danger { + background: color-mix(in srgb, var(--red) 16%, transparent); + border-color: var(--red); + color: var(--red); +} +.btn-success { + background: color-mix(in srgb, var(--green) 16%, transparent); + border-color: var(--green); + color: var(--green); +} +.btn-ghost { + background: transparent; +} +.btn-sm { + padding: 0.25rem 0.55rem; + font-size: 0.78rem; +} + +.field { + display: flex; + flex-direction: column; + gap: 0.28rem; +} +.field-label { + font-size: 0.82rem; + font-weight: 600; +} +.field-help { + font-size: 0.79rem; + color: var(--text-muted); +} +.field-error-text { + font-size: 0.79rem; + color: var(--red); +} +.field-error .input { + border-color: var(--red); +} + +.input { + font: inherit; + font-size: 0.88rem; + width: 100%; + padding: 0.45rem 0.6rem; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--bg-sunken); + color: var(--text); +} +.input:focus { + outline: 2px solid color-mix(in srgb, var(--blue) 55%, transparent); + outline-offset: 1px; + border-color: var(--blue); +} +.textarea { + min-height: 7rem; + resize: vertical; + font-family: var(--mono); + font-size: 0.82rem; +} + +.toggle { + display: inline-flex; + align-items: center; + gap: 0.5rem; + cursor: pointer; + font-size: 0.86rem; +} +.toggle input { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} +.toggle-track { + width: 36px; + height: 20px; + border-radius: 999px; + background: var(--border); + position: relative; + transition: background 0.15s ease; + flex: none; +} +.toggle-track::after { + content: ''; + position: absolute; + top: 2px; + left: 2px; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--text); + transition: transform 0.15s ease; +} +.toggle input:checked + .toggle-track { + background: var(--blue); +} +.toggle input:checked + .toggle-track::after { + transform: translateX(16px); + background: #0c1018; +} +.toggle input:focus-visible + .toggle-track { + outline: 2px solid var(--blue-soft); + outline-offset: 2px; +} + +.table-wrap { + overflow-x: auto; + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.table { + width: 100%; + border-collapse: collapse; + font-size: 0.86rem; +} +.table th, +.table td { + text-align: left; + padding: 0.5rem 0.7rem; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} +.table th { + background: var(--surface); + font-size: 0.76rem; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-muted); + white-space: nowrap; +} +.table tbody tr:last-child td { + border-bottom: none; +} +.table tbody tr:hover { + 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 { + text-align: right; + font-variant-numeric: tabular-nums; +} +.nowrap { + white-space: nowrap; +} + +.empty { + color: var(--text-muted); + font-size: 0.88rem; + padding: 1rem; + text-align: center; + border: 1px dashed var(--border); + border-radius: var(--radius-sm); +} + +.notice { + border-radius: var(--radius-sm); + padding: 0.7rem 0.9rem; + border: 1px solid var(--border); + background: var(--surface); + font-size: 0.88rem; + display: flex; + gap: 0.8rem; + align-items: center; + justify-content: space-between; +} +.notice-error { + border-color: var(--red); + background: color-mix(in srgb, var(--red) 10%, transparent); +} +.notice-warning { + border-color: var(--amber); + background: color-mix(in srgb, var(--amber) 10%, transparent); +} +.notice-success { + border-color: var(--green); + background: color-mix(in srgb, var(--green) 10%, transparent); +} +.notice-info { + border-color: var(--blue); + background: color-mix(in srgb, var(--blue) 10%, transparent); +} + +.loading { + display: flex; + align-items: center; + gap: 0.6rem; + color: var(--text-muted); + padding: 1.6rem; + justify-content: center; +} +.spinner { + width: 16px; + height: 16px; + border: 2px solid var(--border); + border-top-color: var(--blue); + border-radius: 50%; + animation: spin 0.7s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.toast-host { + position: fixed; + right: 1rem; + bottom: 1rem; + display: flex; + flex-direction: column; + gap: 0.5rem; + z-index: 60; +} +.toast { + padding: 0.6rem 0.9rem; + border-radius: var(--radius-sm); + background: var(--bg-elevated); + border: 1px solid var(--border); + box-shadow: var(--shadow); + font-size: 0.87rem; + max-width: 24rem; + animation: toast-in 0.18s ease; +} +.toast-success { + border-color: var(--green); +} +.toast-error { + border-color: var(--red); +} +.toast-info { + border-color: var(--blue); +} +.toast-out { + opacity: 0; + transition: opacity 0.5s ease; +} +@keyframes toast-in { + from { + transform: translateY(8px); + opacity: 0; + } +} + +.overlay { + position: fixed; + inset: 0; + background: rgb(4 8 12 / 62%); + display: grid; + place-items: center; + padding: 1rem; + z-index: 70; +} +.modal { + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + width: min(620px, 100%); + max-height: 88vh; + display: flex; + flex-direction: column; +} +.modal-head { + padding: 0.9rem 1.1rem; + border-bottom: 1px solid var(--border); +} +.modal-body { + padding: 1.1rem; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 0.8rem; +} +.modal-foot { + padding: 0.8rem 1.1rem; + border-top: 1px solid var(--border); + display: flex; + justify-content: flex-end; + gap: 0.5rem; +} + +.rich { + font-size: 0.88rem; +} +.rich h3, +.rich h4 { + margin: 0.7rem 0 0.3rem; +} +.rich ul { + margin: 0.3rem 0; + 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 { + font-size: 0.7rem; + padding: 0 0.2rem; + opacity: 0.75; +} + +.live { + display: flex; + align-items: center; + gap: 0.45rem; + font-size: 0.75rem; + color: var(--text-muted); + padding: 0 0.2rem; +} +.live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-muted); + flex: none; +} +.live[data-status='live'] .live-dot { + background: var(--green); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--green) 25%, transparent); +} +.live[data-status='polling'] .live-dot { + background: var(--amber); +} +.live[data-status='connecting'] .live-dot, +.live[data-status='reconnecting'] .live-dot { + background: var(--blue); + animation: pulse 1.2s ease-in-out infinite; +} +.live[data-status='paused'] .live-dot { + background: var(--border); +} +@keyframes pulse { + 50% { + opacity: 0.25; + } +} + +details summary { + cursor: pointer; + font-size: 0.85rem; + font-weight: 600; + color: var(--text-muted); + padding: 0.35rem 0; + list-style-position: outside; +} +details summary:hover { + color: var(--text); +} +details[open] summary { + margin-bottom: 0.6rem; +} +details > *:not(summary) { + margin-bottom: 0.6rem; +} +details > *:last-child { + 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 ---------------------------------------------- */ + +body[data-mode='simple'] .advanced-only { + display: none !important; +} + +.mode-switch { + display: flex; + border: 1px solid var(--border); + border-radius: 999px; + overflow: hidden; + font-size: 0.78rem; +} +.mode-switch button { + font: inherit; + font-weight: 600; + border: none; + background: transparent; + color: var(--text-muted); + padding: 0.28rem 0.75rem; + cursor: pointer; +} +.mode-switch button.active { + background: var(--blue); + color: #0c1018; +} + +/* --- Login and setup ------------------------------------------------------ */ + +.centered { + min-height: 100vh; + display: grid; + place-items: center; + padding: 1.5rem; +} +.panel { + width: min(520px, 100%); + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + padding: 1.8rem; + display: flex; + flex-direction: column; + gap: 1rem; + text-align: center; +} +.panel .field { + text-align: left; +} + +.wizard { + display: grid; + grid-template-columns: 240px 1fr; + gap: 1.2rem; + align-items: start; +} +.wizard-steps { + display: flex; + flex-direction: column; + gap: 0.2rem; + position: sticky; + top: 1rem; +} +.wizard-step { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.6rem; + border-radius: var(--radius-sm); + border: 1px solid transparent; + background: none; + color: var(--text); + font: inherit; + font-size: 0.86rem; + text-align: left; + cursor: pointer; + width: 100%; +} +.wizard-step:hover { + background: var(--surface); +} +.wizard-step.active { + background: color-mix(in srgb, var(--blue) 16%, transparent); + border-color: var(--blue); +} +.wizard-step .dot { + width: 22px; + height: 22px; + flex: none; + border-radius: 50%; + display: grid; + place-items: center; + font-size: 0.72rem; + font-weight: 700; + border: 1px solid var(--border); + background: var(--bg-sunken); +} +.wizard-step.done .dot { + background: var(--green); + border-color: var(--green); + color: #0c1018; +} +.wizard-step.invalid .dot { + background: var(--red); + border-color: var(--red); + color: #fff; +} + +.steps-list { + margin: 0; + padding-left: 1.2rem; + font-size: 0.87rem; + color: var(--text-muted); +} +.steps-list li { + margin-bottom: 0.3rem; +} +.steps-list strong { + color: var(--text); +} + +.secret-row { + display: flex; + gap: 0.4rem; + align-items: center; +} +.secret-row .input { + flex: 1; +} + +.diff { + font-family: var(--mono); + font-size: 0.8rem; +} +.diff del { + color: var(--red); + text-decoration: line-through; +} +.diff ins { + color: var(--green); + text-decoration: none; +} + +.log-line { + font-family: var(--mono); + font-size: 0.78rem; + padding: 0.18rem 0.4rem; + border-left: 3px solid var(--border); + white-space: pre-wrap; + word-break: break-word; +} +.log-error { + border-left-color: var(--red); +} +.log-warn { + border-left-color: var(--amber); +} +.log-info { + border-left-color: var(--blue); +} +.log-debug { + border-left-color: var(--border); + opacity: 0.75; +} + +.bar { + height: 6px; + border-radius: 999px; + background: var(--bg-sunken); + overflow: hidden; +} +.bar > span { + display: block; + height: 100%; + background: var(--blue); +} + +.repo-list { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 0.8rem; +} +.repo-card { + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.85rem; + background: var(--surface); + display: flex; + flex-direction: column; + gap: 0.45rem; + color: inherit; + text-decoration: none; + cursor: pointer; + transition: + border-color 0.12s ease, + transform 0.12s ease; +} +.repo-card:hover { + 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 { + display: flex; + gap: 0.8rem; + flex-wrap: wrap; + font-size: 0.78rem; + color: var(--text-muted); +} + +.tabs { + display: flex; + gap: 0.3rem; + border-bottom: 1px solid var(--border); + overflow-x: auto; +} +.tabs button { + font: inherit; + font-size: 0.86rem; + font-weight: 600; + background: none; + border: none; + border-bottom: 2px solid transparent; + color: var(--text-muted); + padding: 0.5rem 0.75rem; + cursor: pointer; + white-space: nowrap; +} +.tabs button.active { + color: var(--blue-soft); + 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) { + .shell { + grid-template-columns: 1fr; + } + .sidebar { + position: static; + height: auto; + flex-direction: column; + } + .main { + padding: 1rem; + } + .wizard { + grid-template-columns: 1fr; + } + .wizard-steps { + position: static; + flex-direction: row; + overflow-x: auto; + } + + .palette-overlay { + padding-top: 6vh; + } + + .status-page { + padding: 1.2rem 1rem 2rem; + } + .status-table { + font-size: 0.82rem; + } +} diff --git a/src/web/public/views/community.js b/src/web/public/views/community.js new file mode 100644 index 0000000..f312536 --- /dev/null +++ b/src/web/public/views/community.js @@ -0,0 +1,385 @@ +import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; +import { formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + table, + toast, +} from '../core/ui.js'; + +/** Tickets, polls, temporary voice channels and the bot presence rotation. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const STATUS_TYPES = [ + { value: 'playing', label: 'joue à' }, + { value: 'watching', label: 'regarde' }, + { value: 'listening', label: 'écoute' }, + { value: 'competing', label: 'participe à' }, + { value: 'streaming', label: 'en direct sur' }, +]; + +function ticketsCard(data, level, reload) { + const labels = Object.fromEntries(data.categories.map((category) => [category.id, category.label])); + + return card( + 'Tickets', + { subtitle: `${data.tickets.filter((ticket) => ticket.status === 'open').length} ticket(s) ouvert(s)` }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Catégorie', render: (ticket) => labels[ticket.category_id] ?? ticket.category_id }, + { label: 'Auteur', render: (ticket) => ticket.author_id }, + { + label: 'État', + render: (ticket) => + ticket.status === 'open' ? badge('Ouvert', 'success') : badge('Clôturé', 'neutral'), + }, + { + label: 'Prise en charge', + className: 'advanced-only', + render: (ticket) => ticket.claimed_by ?? '—', + }, + { label: 'Ouvert', className: 'nowrap', render: (ticket) => formatRelative(ticket.created_at) }, + { + label: '', + render: (ticket) => + level >= LEVELS.STAFF && + ticket.status === 'open' && + button( + 'Clôturer', + async () => { + const reason = input({ placeholder: 'Motif de clôture' }); + const confirmed = await modal( + `Clôturer le ticket #${ticket.id}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', { text: 'Le salon privé associé sera supprimé.' }), + field('Motif', reason), + ), + submit: () => true, + }), + { confirmLabel: 'Clôturer', tone: 'danger' }, + ); + if (!confirmed) return; + await api.post(`/api/community/tickets/${ticket.id}/close`, { reason: reason.value }); + toast('Ticket clôturé.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + data.tickets, + { empty: 'Aucun ticket.' }, + ), + ); +} + +function pollsCard(polls, level, reload) { + return card( + 'Sondages', + { subtitle: `${polls.filter((poll) => poll.status === 'open').length} sondage(s) en cours` }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Question', key: 'question' }, + { + label: 'Résultats', + render: (poll) => { + const counts = Object.fromEntries(poll.counts.map((row) => [row.choice_index, row.count])); + const total = poll.counts.reduce((sum, row) => sum + row.count, 0) || 1; + return h( + 'div', + { class: 'stack', style: { gap: '0.2rem' } }, + poll.choices.map((choice, index) => + h( + 'div', + {}, + h( + 'div', + { class: 'row', style: { justifyContent: 'space-between', fontSize: '0.8rem' } }, + h('span', { text: choice }), + h('span', { class: 'muted', text: `${counts[index] ?? 0}` }), + ), + h( + 'div', + { class: 'bar' }, + h('span', { style: { width: `${((counts[index] ?? 0) / total) * 100}%` } }), + ), + ), + ), + ); + }, + }, + { + label: 'État', + render: (poll) => (poll.status === 'open' ? badge('Ouvert', 'success') : badge('Clos', 'neutral')), + }, + { label: 'Fin', className: 'nowrap advanced-only', render: (poll) => formatRelative(poll.ends_at) }, + { + label: '', + render: (poll) => + level >= LEVELS.STAFF && + poll.status === 'open' && + button( + 'Clore', + async () => { + if (!(await confirmAction('Clore le sondage', poll.question))) return; + await api.post(`/api/community/polls/${poll.id}/close`); + toast('Sondage clos.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + polls, + { empty: 'Aucun sondage.' }, + ), + ); +} + +function voiceCard(voice, level, reload) { + return card( + 'Salons vocaux temporaires', + { subtitle: `${voice.channels.filter((channel) => channel.alive).length} salon(s) actif(s)` }, + h('h3', { text: 'Déclencheurs' }), + table( + [ + { label: 'Salon déclencheur', render: (trigger) => trigger.label || trigger.triggerId }, + { label: 'Modèle de nom', render: (trigger) => trigger.template ?? '—' }, + { label: 'Limite', className: 'num', render: (trigger) => trigger.userLimit || '∞' }, + { + label: 'Actif', + render: (trigger) => (trigger.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { label: 'Salons vivants', className: 'num', key: 'activeChannels' }, + { + label: '', + render: (trigger) => + level >= LEVELS.DEV && + button( + trigger.enabled ? 'Mettre en pause' : 'Réactiver', + async () => { + await api.post(`/api/community/voice/triggers/${trigger.triggerId}/toggle`, { + enabled: !trigger.enabled, + }); + toast('Déclencheur mis à jour.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + voice.triggers, + { + empty: + 'Aucun déclencheur configuré. Utilise `/voice setup` sur Discord ou renseigne CHANNEL_VOICE_TRIGGER_ID.', + }, + ), + + h('h3', { text: 'Salons générés' }), + table( + [ + { label: 'Salon', key: 'name' }, + { label: 'Propriétaire', render: (channel) => channel.owner_id }, + { label: 'Occupants', className: 'num', key: 'members' }, + { + label: 'État', + render: (channel) => + h( + 'div', + { class: 'row' }, + channel.alive ? badge('Vivant', 'success') : badge('Fantôme', 'warning'), + channel.locked && badge('Verrouillé', 'info'), + ), + }, + { label: 'Créé', className: 'nowrap', render: (channel) => formatRelative(channel.created_at) }, + { + label: '', + render: (channel) => + level >= LEVELS.STAFF && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le salon', channel.name))) return; + await api.delete(`/api/community/voice/channels/${channel.channel_id}`); + toast('Salon supprimé.'); + reload(); + }, + { tone: 'danger' }, + ), + }, + ], + voice.channels, + { empty: 'Aucun salon temporaire pour l’instant.' }, + ), + ); +} + +function statusesCard(statuses, intervalSeconds, level, reload) { + const interval = input({ type: 'number', value: intervalSeconds, min: 5, style: { maxWidth: '8rem' } }); + + return card( + 'Présence du bot', + { + subtitle: 'Les statuts défilent dans l’ordre d’ajout.', + actions: + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + 'Ajouter un statut', + async () => { + const text = input({ placeholder: 'les issues de FWS Arch' }); + const type = select(STATUS_TYPES, { value: 'watching' }); + const url = input({ placeholder: 'https://twitch.tv/… (type « en direct » uniquement)' }); + + const confirmed = await modal( + 'Nouveau statut', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Type', type), + field('Texte', text), + field('Lien', url), + ), + submit: () => text.value.trim() !== '', + }), + { confirmLabel: 'Ajouter', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post('/api/community/statuses', { + text: text.value, + type: type.value, + url: url.value || undefined, + }); + toast('Statut ajouté.'); + reload(); + }, + { tone: 'primary' }, + ), + ), + }, + + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + field('Rythme de rotation (secondes)', interval), + button( + 'Enregistrer', + async () => { + const result = await api.put('/api/community/statuses/interval', { + seconds: Number(interval.value), + }); + toast(`Rotation réglée sur ${result.intervalSeconds} s. Effective au prochain redémarrage.`); + }, + { tone: 'ghost' }, + ), + ), + + table( + [ + { label: '#', className: 'num', key: 'id' }, + { + label: 'Statut', + render: (status) => { + const type = STATUS_TYPES.find((item) => item.value === status.type); + return `${type?.label ?? status.type} ${status.text}`; + }, + }, + { + label: 'Actif', + render: (status) => (status.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { + label: '', + render: (status) => + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + status.enabled ? 'Pause' : 'Activer', + async () => { + await api.patch(`/api/community/statuses/${status.id}`, { enabled: !status.enabled }); + toast('Statut mis à jour.'); + reload(); + }, + { tone: 'ghost' }, + ), + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le statut', status.text))) return; + await api.delete(`/api/community/statuses/${status.id}`); + toast('Statut supprimé.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ], + statuses, + { empty: 'Aucun statut : le bot affiche sa ligne par défaut.' }, + ), + ); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + autoRefresh(reload, { topics: ['community', 'discord', 'tick'] }); + + return renderAsync( + host, + async () => { + const [tickets, polls, voice, statuses] = await Promise.all([ + api.get('/api/community/tickets', { limit: 100 }), + api.get('/api/community/polls', { limit: 30 }), + api.get('/api/community/voice'), + api.get('/api/community/statuses'), + ]); + return { tickets, polls: polls.polls, voice, statuses }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Tickets & vocaux' }), + h('p', { class: 'muted', text: 'Le quotidien de la communauté, géré depuis le site.' }), + ), + ), + data.voice.triggers.length === 0 && + notice('Aucun salon « rejoindre pour créer » : la fonctionnalité vocale reste inactive.', 'info'), + ticketsCard(data.tickets, level, reload), + pollsCard(data.polls, level, reload), + voiceCard(data.voice, level, reload), + statusesCard(data.statuses.statuses, data.statuses.intervalSeconds, level, reload), + ), + ); +} diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js new file mode 100644 index 0000000..785a809 --- /dev/null +++ b/src/web/public/views/deployments.js @@ -0,0 +1,389 @@ +import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; +import { formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + table, + toast, + toggle, +} from '../core/ui.js'; + +/** Deploy targets and deployment history — the operations side of the SaaS (M16-T06). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const STATUS_TONE = { + success: 'success', + failed: 'danger', + running: 'warning', + pending: 'neutral', + cancelled: 'neutral', +}; + +const KINDS = [ + { value: 'webhook', label: 'Webhook signé (recommandé)' }, + { value: 'gitea-action', label: 'Workflow Gitea Actions' }, + { value: 'command', label: 'Commande shell sur l’hôte du bot' }, +]; + +const KIND_HELP = { + webhook: + 'Le bot envoie une requête POST signée en HMAC-SHA256 à ton serveur. C’est la méthode la plus sûre : rien ne s’exécute sur la machine du bot.', + 'gitea-action': + 'Le bot déclenche un workflow Gitea Actions. Le workflow doit accepter `workflow_dispatch`.', + command: + 'Le bot exécute une commande shell sur sa propre machine. À réserver à des personnes de confiance : c’est une exécution de code arbitraire.', +}; + +async function editTarget(existing, repositories, commandsAllowed, level, reload) { + const name = input({ value: existing?.name ?? '', placeholder: 'production-web' }); + + // A webhook or a shell command needs no Gitea at all, so an unreachable forge + // must not stand between the user and a deploy target: the repository then + // falls back to a free-text field. + const repository = + repositories.length > 0 + ? select( + repositories.map((item) => ({ value: item.fullName, label: item.fullName })), + { value: existing?.repository ?? repositories[0]?.fullName }, + ) + : input({ value: existing?.repository ?? '', placeholder: 'FWS/FWS-Arch' }); + const environment = input({ value: existing?.environment ?? 'production' }); + const kindOptions = KINDS.filter( + (kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER), + ); + const kind = select(kindOptions, { value: existing?.kind ?? 'webhook' }); + + const url = input({ value: existing?.config?.url ?? '', placeholder: 'https://deploy.exemple.org/hook' }); + const secret = input({ + type: 'password', + placeholder: existing?.config?.hasSecret ? 'Inchangé' : 'Secret HMAC', + }); + const command = input({ + value: existing?.config?.command ?? '', + placeholder: 'systemctl restart fws-arch', + }); + const cwd = input({ + value: existing?.config?.cwd ?? '', + placeholder: 'Répertoire de travail (facultatif)', + }); + const workflow = input({ value: existing?.config?.workflow ?? '', placeholder: 'deploy.yml' }); + const ref = input({ value: existing?.config?.ref ?? '', placeholder: 'main' }); + + let autoDeploy = existing?.autoDeploy ?? false; + let enabled = existing?.enabled ?? true; + + const specific = h('div', { class: 'stack' }); + const help = h('p', { class: 'muted' }); + + const drawSpecific = () => { + help.textContent = KIND_HELP[kind.value]; + const fields = { + webhook: [ + field('URL', url), + field('Secret partagé', secret, { + help: 'Envoyé en en-tête `X-FWS-Signature` (HMAC-SHA256 du corps JSON).', + }), + ], + command: [field('Commande', command), field('Répertoire de travail', cwd)], + 'gitea-action': [ + field('Fichier de workflow', workflow, { help: 'Nom du fichier dans `.gitea/workflows/`.' }), + field('Référence', ref, { help: 'Branche ou tag sur lequel déclencher le workflow.' }), + ], + }; + mount(specific, fields[kind.value] ?? []); + }; + kind.addEventListener('change', drawSpecific); + drawSpecific(); + + const confirmed = await modal( + existing ? `Modifier « ${existing.name} »` : 'Nouvelle cible de déploiement', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom', name), + field('Dépôt', repository, { + help: + repositories.length > 0 + ? undefined + : 'Format `organisation/depot`. La liste est vide : Gitea est injoignable ou non configuré.', + }), + field('Environnement', environment, { help: 'production, staging, preview…' }), + field('Type', kind), + help, + specific, + toggle( + autoDeploy, + (checked) => (autoDeploy = checked), + 'Déployer automatiquement à chaque release publiée', + ), + toggle(enabled, (checked) => (enabled = checked), 'Cible active'), + ), + submit: () => name.value.trim() !== '' && repository.value.trim() !== '', + }), + { confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const config = {}; + if (kind.value === 'webhook') { + config.url = url.value.trim(); + if (secret.value) config.secret = secret.value; + } else if (kind.value === 'command') { + config.command = command.value.trim(); + config.cwd = cwd.value.trim(); + } else { + config.workflow = workflow.value.trim(); + config.ref = ref.value.trim(); + } + + const payload = { + name: name.value.trim(), + repository: repository.value, + environment: environment.value.trim(), + kind: kind.value, + config, + autoDeploy, + enabled, + }; + + if (existing) await api.patch(`/api/deploy/targets/${existing.id}`, payload); + else await api.post('/api/deploy/targets', payload); + + toast(existing ? 'Cible mise à jour.' : 'Cible créée.'); + reload(); +} + +async function runTarget(target, requireConfirmation, reload) { + const releaseTag = input({ placeholder: 'v1.2.3 (facultatif)' }); + const ref = input({ placeholder: 'main (facultatif)' }); + + const confirmed = await modal( + `Déployer « ${target.name} »`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', {}, 'Environnement : ', h('strong', { text: target.environment })), + h('p', { class: 'muted', text: target.summary }), + field('Version à déployer', releaseTag), + field('Référence git', ref), + requireConfirmation && h('p', { class: 'muted', text: 'Le déploiement démarre dès la validation.' }), + ), + submit: () => true, + }), + { confirmLabel: 'Déployer', tone: 'primary' }, + ); + if (!confirmed) return; + + toast('Déploiement lancé…', 'info'); + const result = await api.post(`/api/deploy/targets/${target.id}/run`, { + releaseTag: releaseTag.value.trim() || undefined, + ref: ref.value.trim() || undefined, + }); + + toast( + result.status === 'success' + ? 'Déploiement réussi.' + : `Déploiement en échec : ${result.error ?? 'raison inconnue'}`, + result.status === 'success' ? 'success' : 'error', + ); + reload(); +} + +const showLog = (deployment) => + modal(`Déploiement #${deployment.id}`, () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', {}, h('strong', { text: deployment.target_name }), ` · ${deployment.environment}`), + h('p', { + class: 'muted', + text: `${deployment.repository} · ${deployment.release_tag ?? deployment.ref ?? '—'}`, + }), + deployment.error && h('p', { class: 'field-error-text', text: deployment.error }), + h('pre', {}, h('code', { text: deployment.log || 'Aucune sortie.' })), + ), + submit: () => true, + })); + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + // A running deployment reports itself, so the log lands without a reload. + autoRefresh(reload, { topics: ['deployments', 'tick'], minIntervalMs: 2000 }); + + return renderAsync( + host, + async () => { + // The repository list is a convenience, not a prerequisite: a Gitea that + // answers 403 must not take the whole deployment page down with it. + const [targets, deployments, repositories] = await Promise.all([ + api.get('/api/deploy/targets'), + api.get('/api/deployments', { limit: 40 }), + api.get('/api/repositories').catch((error) => ({ repositories: [], error: error.message })), + ]); + return { + ...targets, + deployments: deployments.deployments, + repositories: repositories.repositories ?? [], + repositoriesError: repositories.error ?? null, + }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Déploiements' }), + h('p', { + class: 'muted', + text: 'Déclare où livrer chaque dépôt, puis déploie à la demande ou automatiquement à chaque release.', + }), + ), + level >= LEVELS.DEV && + button( + 'Nouvelle cible', + () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'primary' }, + ), + ), + + data.repositoriesError && + notice( + `Liste des dépôts indisponible (${data.repositoriesError}). Tu peux quand même créer une cible en saisissant le dépôt à la main ; seules les cibles Gitea Actions ont réellement besoin de la forge.`, + 'warning', + ), + + !data.commandDeploysAllowed && + notice( + 'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.', + 'info', + ), + + card( + 'Cibles', + { subtitle: `${data.targets.length} cible(s) configurée(s)` }, + table( + [ + { + label: 'Cible', + render: (target) => + h( + 'div', + {}, + h('strong', { text: target.name }), + h('div', { class: 'muted', text: target.summary }), + ), + }, + { label: 'Dépôt', key: 'repository' }, + { label: 'Environnement', render: (target) => badge(target.environment, 'info') }, + { + label: 'Type', + className: 'advanced-only', + render: (target) => badge(target.kind, target.kind === 'command' ? 'warning' : 'neutral'), + }, + { + label: 'Auto', + render: (target) => + target.autoDeploy ? badge('Auto', 'success') : badge('Manuel', 'neutral'), + }, + { + label: 'Actif', + render: (target) => (target.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { + label: '', + render: (target) => + h( + 'div', + { class: 'row' }, + level >= LEVELS.DEV && + button('Déployer', () => runTarget(target, true, reload), { + tone: 'primary', + disabled: !target.enabled, + }), + level >= LEVELS.DEV && + button( + 'Modifier', + () => + editTarget(target, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'ghost' }, + ), + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la cible', `Supprimer « ${target.name} » ?`))) + return; + await api.delete(`/api/deploy/targets/${target.id}`); + toast('Cible supprimée.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ], + data.targets, + { + // The action that fills the table belongs in the table, not only + // in the page header where nobody looks for it. + empty: h( + 'div', + { class: 'stack', style: { alignItems: 'center' } }, + h('p', { + text: 'Aucune cible pour l’instant. Une cible dit où livrer un dépôt ; le bouton « Déployer » apparaît ensuite sur sa ligne.', + }), + level >= LEVELS.DEV + ? button( + 'Créer une première cible', + () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'primary' }, + ) + : h('p', { class: 'muted', text: 'Le niveau Dev est requis pour en créer une.' }), + ), + }, + ), + ), + + card( + 'Historique', + { subtitle: 'Les 40 derniers déploiements, réussis comme échoués.' }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Cible', key: 'target_name' }, + { label: 'Environnement', key: 'environment' }, + { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' }, + { + label: 'État', + render: (row) => badge(row.status, STATUS_TONE[row.status] ?? 'neutral'), + }, + { label: 'Source', className: 'advanced-only', key: 'source' }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) }, + { label: '', render: (row) => button('Journal', () => showLog(row), { tone: 'ghost' }) }, + ], + data.deployments, + { empty: 'Aucun déploiement enregistré.' }, + ), + ), + ), + ); +} diff --git a/src/web/public/views/discord.js b/src/web/public/views/discord.js new file mode 100644 index 0000000..bc96aca --- /dev/null +++ b/src/web/public/views/discord.js @@ -0,0 +1,462 @@ +import { api } from '../core/api.js'; +import { formatDate, formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + spinner, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Discord server console: members, roles, moderation, announcements, routing. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; +const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' }; +const ACCESS_TONE = { 0: 'neutral', 1: 'info', 2: 'success', 3: 'danger' }; + +const DURATIONS = [ + { value: String(5 * 60_000), label: '5 minutes' }, + { value: String(60 * 60_000), label: '1 heure' }, + { value: String(24 * 60 * 60_000), label: '1 jour' }, + { value: String(7 * 24 * 60 * 60_000), label: '7 jours' }, +]; + +const MODERATION_ACTIONS = [ + { value: 'warn', label: 'Avertissement' }, + { value: 'mute', label: 'Exclusion temporaire' }, + { value: 'kick', label: 'Expulsion' }, + { value: 'ban', label: 'Bannissement' }, +]; + +async function moderate(member, reload) { + const action = select(MODERATION_ACTIONS, { value: 'warn' }); + const reason = input({ placeholder: 'Motif communiqué au membre' }); + const duration = select(DURATIONS, { value: DURATIONS[1].value }); + const durationField = field('Durée', duration); + durationField.style.display = 'none'; + + action.addEventListener('change', () => { + durationField.style.display = action.value === 'mute' ? '' : 'none'; + }); + + const confirmed = await modal( + `Modérer ${member.displayName}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + notice( + 'Le barème de rôles s’applique : tu ne peux pas agir sur quelqu’un au moins aussi haut placé.', + 'info', + ), + field('Action', action), + field('Motif', reason), + durationField, + ), + submit: () => true, + }), + { confirmLabel: 'Appliquer', tone: 'danger' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/discord/moderation', { + action: action.value, + userId: member.id, + reason: reason.value, + durationMs: action.value === 'mute' ? Number(duration.value) : undefined, + }); + toast(`${result.label} appliqué.`); + reload(); +} + +async function manageRoles(member, roles, reload) { + const picker = select( + roles.filter((role) => !role.managed).map((role) => ({ value: role.id, label: role.name })), + {}, + ); + const current = h( + 'div', + { class: 'row' }, + member.roles.map((roleId) => { + const role = roles.find((item) => item.id === roleId); + return badge(role?.name ?? roleId, 'info'); + }), + ); + let mode = 'add'; + + const confirmed = await modal( + `Rôles de ${member.displayName}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('h3', { text: 'Rôles actuels' }), + member.roles.length > 0 ? current : h('p', { class: 'muted', text: 'Aucun rôle.' }), + field( + 'Action', + select( + [ + { value: 'add', label: 'Ajouter' }, + { value: 'remove', label: 'Retirer' }, + ], + { value: 'add', onChange: (event) => (mode = event.target.value) }, + ), + ), + field('Rôle', picker), + ), + submit: () => true, + }), + { confirmLabel: 'Appliquer' }, + ); + if (!confirmed) return; + + await api.post(`/api/discord/members/${member.id}/roles`, { roleId: picker.value, action: mode }); + toast('Rôles mis à jour.'); + reload(); +} + +async function announce(channels) { + const channel = select( + channels + .filter((item) => item.kind === 'text' || item.kind === 'announcement') + .map((item) => ({ value: item.id, label: `#${item.name}` })), + {}, + ); + const title = input({ placeholder: 'Titre (facultatif)' }); + const content = textarea({ placeholder: 'Ton message…' }); + let asEmbed = true; + + const confirmed = await modal( + 'Publier une annonce', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Salon', channel), + field('Titre', title), + field('Message', content), + toggle(true, (checked) => (asEmbed = checked), 'Publier sous forme d’embed'), + ), + submit: () => content.value.trim() !== '' || title.value.trim() !== '', + }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/discord/announce', { + channelId: channel.value, + title: title.value, + content: content.value, + asEmbed, + }); + toast(`Annonce publiée (${result.messageId}).`); +} + +function membersCard(guild, level, initialSearch = '') { + const host = h('div', { class: 'stack' }); + // 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 = () => + renderAsync( + host, + () => api.get('/api/discord/members', { q: search.value.trim(), limit: 100 }), + (data) => + table( + [ + { + label: 'Membre', + render: (member) => + h( + 'div', + { class: 'row' }, + h('img', { + src: member.avatar, + alt: '', + width: 26, + height: 26, + style: { borderRadius: '50%' }, + }), + h( + 'div', + {}, + h('strong', { text: member.displayName }), + h('div', { class: 'muted', text: `@${member.username}` }), + ), + ), + }, + { + label: 'Niveau', + render: (member) => badge(ACCESS_LABELS[member.accessLevel], ACCESS_TONE[member.accessLevel]), + }, + { + label: 'Arrivé', + className: 'nowrap advanced-only', + render: (member) => formatRelative(member.joinedAt), + }, + { + label: 'État', + render: (member) => + member.timeoutUntil && new Date(member.timeoutUntil) > new Date() + ? badge('Exclu', 'warning') + : member.bot + ? badge('Bot', 'neutral') + : '—', + }, + { + label: '', + render: (member) => + h( + 'div', + { class: 'row' }, + level >= LEVELS.STAFF && button('Modérer', () => moderate(member, load), { tone: 'ghost' }), + level >= LEVELS.DEV && + button('Rôles', () => manageRoles(member, guild.roles, load), { tone: 'ghost' }), + ), + }, + ], + data.members, + { empty: 'Aucun membre ne correspond.' }, + ), + ); + + let timer = null; + search.addEventListener('input', () => { + clearTimeout(timer); + timer = setTimeout(load, 300); + }); + load(); + + return card('Membres', { subtitle: `${guild.memberCount} membre(s)`, actions: search }, host); +} + +function notificationsCard(guild, level) { + const host = h('div', { class: 'stack' }); + + const load = () => + renderAsync( + host, + () => api.get('/api/discord/notifications'), + (data) => { + const overrides = Object.fromEntries(data.overrides.map((row) => [row.type, row.channel_id])); + const channels = guild.channels.filter( + (item) => item.kind === 'text' || item.kind === 'announcement', + ); + + return table( + [ + { label: 'Type', key: 'type' }, + { + label: 'Salon par défaut (.env)', + className: 'advanced-only', + render: (row) => { + const channel = guild.channels.find((item) => item.id === row.fallback); + return channel ? `#${channel.name}` : '—'; + }, + }, + { + label: 'Salon utilisé', + render: (row) => { + if (level < LEVELS.STAFF) return row.current ? `#${row.current}` : '—'; + const picker = select( + [ + { value: '', label: 'Valeur par défaut du .env' }, + ...channels.map((item) => ({ value: item.id, label: `#${item.name}` })), + ], + { + value: overrides[row.type] ?? '', + onChange: async (event) => { + await api.put(`/api/discord/notifications/${row.type}`, { + channelId: event.target.value, + }); + toast('Routage mis à jour.'); + }, + }, + ); + return picker; + }, + }, + ], + Object.keys(data.defaults).map((type) => ({ + type, + fallback: data.defaults[type], + current: overrides[type] ?? data.defaults[type], + })), + ); + }, + ); + + load(); + return card( + 'Notifications', + { subtitle: 'Où le bot publie les événements Gitea et ses propres messages.' }, + host, + ); +} + +/** `#/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 }) { + const level = state.me.accessLevel; + mount(host, spinner()); + + let guild; + try { + guild = await api.get('/api/discord/guild'); + } catch (error) { + mount(host, notice(error.message, 'error')); + return; + } + + const byKind = (kind) => guild.channels.filter((channel) => channel.kind === kind).length; + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + { class: 'row' }, + guild.icon && + h('img', { src: guild.icon, alt: '', width: 48, height: 48, style: { borderRadius: '12px' } }), + h( + 'div', + {}, + h('h1', { text: guild.name }), + h('p', { class: 'muted', text: `Créé le ${formatDate(guild.createdAt)}` }), + ), + ), + level >= LEVELS.STAFF && + button('Publier une annonce', () => announce(guild.channels), { tone: 'primary' }), + ), + + card( + 'Serveur', + {}, + grid( + stat('Membres', guild.memberCount, { tone: 'primary' }), + stat('Salons texte', byKind('text')), + stat('Salons vocaux', byKind('voice')), + stat('Rôles', guild.roles.length), + stat('Boosts', guild.boostCount ?? 0), + stat('Niveau de boost', guild.boostTier), + ), + ), + + membersCard(guild, level, memberQuery()), + + card( + 'Rôles', + { advanced: true, subtitle: 'Ordre hiérarchique, du plus élevé au plus bas.' }, + table( + [ + { + label: 'Rôle', + render: (role) => + h( + 'div', + { class: 'row' }, + h('span', { + style: { + width: '12px', + height: '12px', + borderRadius: '50%', + background: role.color === '#000000' ? 'var(--border)' : role.color, + display: 'inline-block', + }, + }), + h('span', { text: role.name }), + ), + }, + { label: 'Membres', className: 'num', key: 'memberCount' }, + { label: 'Position', className: 'num', key: 'position' }, + { + label: 'Rôle FWS', + render: (role) => { + const mapping = Object.entries(guild.mapping.roles).find(([, id]) => id === role.id); + return mapping ? badge(mapping[0], 'success') : '—'; + }, + }, + ], + guild.roles, + ), + ), + + notificationsCard(guild, level), + + card( + 'Commandes slash', + { + 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(), + ), + ), + ); +} + +async function renderCommands() { + const host = h('div', {}); + renderAsync( + host, + () => api.get('/api/discord/commands'), + (data) => + table( + [ + { label: 'Commande', render: (command) => `/${command.name}` }, + { label: 'Description', key: 'description' }, + { label: 'Niveau', render: (command) => badge(command.accessLabel, ACCESS_TONE[command.access]) }, + { + label: 'Sous-commandes', + render: (command) => (command.options ?? []).map((option) => option.name).join(', ') || '—', + }, + ], + data.commands, + ), + ); + return host; +} diff --git a/src/web/public/views/login.js b/src/web/public/views/login.js new file mode 100644 index 0000000..bf7f899 --- /dev/null +++ b/src/web/public/views/login.js @@ -0,0 +1,97 @@ +import { api } from '../core/api.js'; +import { h, mount } from '../core/dom.js'; +import { button, field, input, notice, toast } from '../core/ui.js'; + +/** Sign-in page: Discord OAuth2, or the bootstrap token when nothing is configured yet. */ + +const ERRORS = { + 'oauth-not-configured': + 'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET`, puis redémarre le bot.', + 'state-mismatch': 'La session de connexion a expiré. Réessaie.', + 'exchange-failed': + 'Discord a refusé l’échange du code : la redirection déclarée dans le portail ne correspond pas à celle ci-dessous.', + 'not-a-member': 'Ton compte Discord n’est pas membre du serveur FWS.', + 'insufficient-level': 'Ton compte n’a pas le rôle Staff, Dev ou Owner sur le serveur.', + 'missing-code': 'Discord n’a pas renvoyé de code d’autorisation.', + access_denied: 'Connexion annulée.', +}; + +export function render(host, { state }) { + const params = new URLSearchParams(window.location.hash.split('?')[1] ?? ''); + const failure = params.get('error'); + const config = state.config ?? {}; + + const tokenInput = input({ type: 'password', placeholder: 'Jeton d’amorçage', autocomplete: 'off' }); + + const submitSetupToken = async () => { + try { + await api.post('/api/auth/setup', { token: tokenInput.value.trim() }); + window.location.hash = '#/setup'; + window.location.reload(); + } catch (error) { + toast(error.message, 'error'); + } + }; + + mount( + host, + h( + 'div', + { class: 'centered' }, + h( + 'div', + { class: 'panel' }, + h('img', { src: 'favicon.svg', alt: '', width: 56, height: 56, style: { margin: '0 auto' } }), + h('h1', { text: 'FWS-Bot' }), + h('p', { class: 'muted', text: 'Administration du bot, de l’organisation et des déploiements.' }), + + failure && notice(ERRORS[failure] ?? `Connexion refusée (${failure}).`, 'error'), + + config.oauthConfigured + ? h('a', { class: 'btn btn-primary', href: '/auth/login', text: 'Se connecter avec Discord' }) + : notice( + 'La connexion Discord n’est pas encore disponible. Utilise le jeton d’amorçage pour ouvrir l’assistant de configuration.', + 'warning', + ), + + // The redirect is derived from the address in use, so it is the exact + // value to paste in the portal — port included. + config.redirectUri && + h( + 'details', + { class: 'muted', style: { textAlign: 'left', width: '100%' } }, + h('summary', { text: 'Redirection OAuth2 à déclarer dans le Developer Portal' }), + h('pre', {}, h('code', { text: config.redirectUri })), + h('p', { + text: 'Developer Portal → ton application → OAuth2 → Redirects. Elle doit être identique au caractère près, port compris.', + }), + ), + + // Always reachable: when Discord sign-in is broken or not set up yet, + // this is the only way back into the configuration, and hiding it left + // no visible way out. + h( + 'details', + { class: 'stack', style: { textAlign: 'left', width: '100%' }, open: !config.oauthConfigured }, + h('summary', { text: 'Se connecter avec un jeton de configuration' }), + field('Jeton d’amorçage', tokenInput, { + help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration, jamais au reste du site.', + }), + !config.setupAvailable && + notice( + 'Aucun jeton n’est configuré pour l’instant. Renseigne `WEB_SETUP_TOKEN` dans le .env puis redémarre le bot, ou lance `npm run setup` pour en obtenir un temporaire.', + 'info', + ), + button('Ouvrir l’assistant de configuration', submitSetupToken, { + tone: 'ghost', + disabled: !config.setupAvailable, + }), + ), + ), + ), + ); + + tokenInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') submitSetupToken(); + }); +} diff --git a/src/web/public/views/logs.js b/src/web/public/views/logs.js new file mode 100644 index 0000000..901a4a5 --- /dev/null +++ b/src/web/public/views/logs.js @@ -0,0 +1,155 @@ +import { api } from '../core/api.js'; +import { formatBytes, formatDate, formatRelative, h, mount } from '../core/dom.js'; +import { badge, button, card, renderAsync, select, table, toast } from '../core/ui.js'; + +/** Functional event log and daily technical log files. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +function eventsCard() { + const host = h('div', { class: 'stack' }); + let typeFilter = ''; + + const load = () => + renderAsync( + host, + () => api.get('/api/logs/events', { type: typeFilter, limit: 150 }), + (data) => + h( + 'div', + { class: 'stack' }, + select( + [ + { value: '', label: 'Tous les événements' }, + ...data.types.map((row) => ({ value: row.type, label: `${row.type} (${row.count})` })), + ], + { + value: typeFilter, + onChange: (event) => { + typeFilter = event.target.value; + load(); + }, + }, + ), + table( + [ + { label: 'Type', render: (event) => badge(event.type, 'info') }, + { label: 'Auteur', render: (event) => event.actor_id ?? '—' }, + { + label: 'Détail', + render: (event) => (event.payload ? JSON.stringify(event.payload) : '—'), + }, + { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) }, + ], + data.events, + { empty: 'Aucun événement enregistré.' }, + ), + ), + ); + + load(); + return card('Événements fonctionnels', { subtitle: 'Ce que le bot a fait, et pour qui.' }, host); +} + +function filesCard() { + const host = h('div', { class: 'stack' }); + const viewer = h('div', { class: 'stack' }); + let levelFilter = ''; + + const openFile = (name) => + renderAsync( + viewer, + () => api.get(`/api/logs/files/${name}`, { lines: 400, level: levelFilter }), + (data) => + card( + data.name, + { + actions: select( + [ + { value: '', label: 'Tous les niveaux' }, + { value: 'debug', label: 'debug' }, + { value: 'info', label: 'info' }, + { value: 'warn', label: 'warn' }, + { value: 'error', label: 'error' }, + ], + { + value: levelFilter, + onChange: (event) => { + levelFilter = event.target.value; + openFile(name); + }, + }, + ), + }, + h( + 'div', + { class: 'stack', style: { gap: '0.1rem', maxHeight: '28rem', overflowY: 'auto' } }, + data.entries.length === 0 + ? h('p', { class: 'empty', text: 'Aucune ligne pour ce filtre.' }) + : data.entries.map((entry) => + h('div', { + class: `log-line log-${entry.level ?? 'info'}`, + text: `${entry.time ? formatDate(entry.time) : ''} [${entry.scope ?? '—'}] ${entry.message ?? ''}${ + entry.meta ? ` ${JSON.stringify(entry.meta)}` : '' + }`, + }), + ), + ), + ), + ); + + renderAsync( + host, + () => api.get('/api/logs/files'), + (data) => + table( + [ + { label: 'Fichier', key: 'name' }, + { label: 'Taille', className: 'num', render: (file) => formatBytes(file.sizeBytes) }, + { label: 'Modifié', className: 'nowrap', render: (file) => formatRelative(file.modifiedAt) }, + { label: '', render: (file) => button('Ouvrir', () => openFile(file.name), { tone: 'ghost' }) }, + ], + data.files, + { empty: 'Aucun fichier de log.' }, + ), + ); + + return h( + 'div', + { class: 'stack' }, + card('Journaux techniques', { subtitle: 'Un fichier JSON par jour, secrets masqués.' }, host), + viewer, + ); +} + +export function render(host, { state }) { + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Journaux' }), + h('p', { class: 'muted', text: 'Ce que le bot a fait et ce qu’il a rencontré.' }), + ), + state.me.accessLevel >= LEVELS.OWNER && + button( + 'Purger les anciens événements', + async () => { + const result = await api.post('/api/settings/purge', {}); + toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`); + render(host, { state }); + }, + { tone: 'ghost' }, + ), + ), + eventsCard(), + state.me.accessLevel >= LEVELS.DEV ? filesCard() : null, + ), + ); +} diff --git a/src/web/public/views/organization.js b/src/web/public/views/organization.js new file mode 100644 index 0000000..4df1e59 --- /dev/null +++ b/src/web/public/views/organization.js @@ -0,0 +1,291 @@ +import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; +import { formatBytes, formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + field, + grid, + input, + modal, + renderAsync, + select, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Organization page: identity, members, teams and repository inventory. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +async function editOrganization(data, refresh) { + const fullName = input({ value: data.fullName ?? '' }); + const description = textarea({ value: data.description ?? '' }); + const website = input({ value: data.website ?? '', placeholder: 'https://…' }); + const location = input({ value: data.location ?? '' }); + const visibility = select( + [ + { value: 'public', label: 'Publique' }, + { value: 'limited', label: 'Limitée aux comptes connectés' }, + { value: 'private', label: 'Privée' }, + ], + { value: data.visibility ?? 'public' }, + ); + + const confirmed = await modal( + 'Modifier l’organisation', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom affiché', fullName), + field('Description', description), + field('Site web', website), + field('Localisation', location), + field('Visibilité', visibility), + ), + submit: () => true, + }), + { confirmLabel: 'Enregistrer' }, + ); + if (!confirmed) return; + + await api.patch('/api/organization', { + full_name: fullName.value, + description: description.value, + website: website.value, + location: location.value, + visibility: visibility.value, + }); + toast('Organisation mise à jour.'); + refresh(); +} + +async function createRepository(refresh) { + const name = input({ placeholder: 'mon-nouveau-depot' }); + const description = input({ placeholder: 'À quoi sert ce dépôt ?' }); + const defaultBranch = input({ value: 'main' }); + let isPrivate = false; + let autoInit = true; + + const confirmed = await modal( + 'Créer un dépôt', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom', name, { help: 'Lettres, chiffres, points, tirets et soulignés.' }), + field('Description', description), + field('Branche par défaut', defaultBranch), + toggle(false, (checked) => (isPrivate = checked), 'Dépôt privé'), + toggle(true, (checked) => (autoInit = checked), 'Initialiser avec un README'), + ), + submit: () => name.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const created = await api.post('/api/organization/repositories', { + name: name.value.trim(), + description: description.value, + defaultBranch: defaultBranch.value, + private: isPrivate, + autoInit, + }); + toast(`Dépôt ${created.fullName} créé.`); + refresh(); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const refresh = () => render(host, { state }); + + autoRefresh(refresh, { topics: ['gitea'] }); + + return renderAsync( + host, + () => api.get('/api/organization'), + (data) => { + const totals = data.repositories.reduce( + (accumulator, repository) => ({ + issues: accumulator.issues + (repository.openIssues ?? 0), + pulls: accumulator.pulls + (repository.openPulls ?? 0), + size: accumulator.size + (repository.sizeKb ?? 0) * 1024, + }), + { issues: 0, pulls: 0, size: 0 }, + ); + + return h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: data.fullName || data.name }), + h('p', { class: 'muted', text: data.description || 'Organisation Gitea de FWS.' }), + ), + h( + 'div', + { class: 'row' }, + h('a', { + class: 'btn btn-ghost', + href: data.url, + target: '_blank', + rel: 'noreferrer', + text: '↗ Voir sur Gitea', + }), + level >= LEVELS.DEV && + button('Nouveau dépôt', () => createRepository(refresh), { tone: 'primary' }), + level >= LEVELS.OWNER && + button('Modifier', () => editOrganization(data, refresh), { tone: 'ghost' }), + ), + ), + + card( + 'Chiffres clés', + {}, + grid( + stat('Dépôts', data.repositories.length, { tone: 'primary' }), + stat('Membres', data.members.length), + stat('Équipes', data.teams.length), + stat('Issues ouvertes', totals.issues, { tone: totals.issues > 0 ? 'warning' : 'neutral' }), + stat('PR ouvertes', totals.pulls), + stat('Taille totale', formatBytes(totals.size)), + ), + ), + + card( + 'Dépôts', + { subtitle: 'Clique sur une ligne pour gérer le dépôt en détail.' }, + table( + [ + { + label: 'Dépôt', + render: (repository) => + h( + 'div', + {}, + h('a', { href: `#/repos/${repository.fullName}`, text: repository.name }), + repository.description && h('div', { class: 'muted', text: repository.description }), + ), + }, + { + label: 'État', + render: (repository) => + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + repository.fork && badge('Fork', 'info'), + ), + }, + { + label: 'Langage', + render: (repository) => repository.language || '—', + className: 'advanced-only', + }, + { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 }, + { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 }, + { + label: 'Releases', + className: 'num advanced-only', + render: (repository) => repository.releases ?? 0, + }, + { + label: 'Mise à jour', + className: 'nowrap', + render: (repository) => formatRelative(repository.updatedAt), + }, + ], + data.repositories, + { + empty: 'Aucun dépôt dans cette organisation.', + rowHref: (repository) => `#/repos/${repository.fullName}`, + }, + ), + ), + + card( + 'Membres', + { subtitle: `${data.members.length} compte(s) Gitea` }, + table( + [ + { + label: 'Compte', + render: (member) => + h( + 'div', + { class: 'row' }, + member.avatar && + h('img', { + src: member.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: member.login }), + ), + }, + { label: 'Nom', render: (member) => member.fullName || '—' }, + { label: 'Admin', render: (member) => (member.isAdmin ? badge('Admin', 'danger') : '—') }, + { + label: 'Dernière connexion', + className: 'nowrap advanced-only', + render: (member) => formatRelative(member.lastLogin), + }, + ], + data.members, + ), + ), + + card( + 'Équipes', + { advanced: true }, + table( + [ + { label: 'Équipe', key: 'name' }, + { label: 'Description', render: (team) => team.description || '—' }, + { label: 'Permission', render: (team) => badge(team.permission ?? '—', 'info') }, + { + label: 'Tous les dépôts', + render: (team) => (team.includesAllRepositories ? 'Oui' : 'Non'), + }, + { + label: '', + render: (team) => + button( + 'Membres', + async () => { + const { members } = await api.get(`/api/organization/teams/${team.id}/members`); + await modal(`Membres de ${team.name}`, () => ({ + node: table( + [ + { label: 'Compte', key: 'login' }, + { label: 'Nom', render: (m) => m.fullName || '—' }, + ], + members, + ), + submit: () => true, + })); + }, + { tone: 'ghost' }, + ), + }, + ], + data.teams, + ), + ), + ); + }, + ); +} diff --git a/src/web/public/views/overview.js b/src/web/public/views/overview.js new file mode 100644 index 0000000..a1b9396 --- /dev/null +++ b/src/web/public/views/overview.js @@ -0,0 +1,211 @@ +import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; +import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js'; +import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js'; + +/** Landing page: state of the bot, the organization and the last deployments. */ + +const TONE = { + success: 'success', + failed: 'danger', + running: 'warning', + pending: 'neutral', + cancelled: 'neutral', +}; + +const EVENT_LABELS = { + 'web.login': 'Connexion au tableau de bord', + 'web.release.create': 'Release publiée', + 'deploy.success': 'Déploiement réussi', + 'deploy.failed': 'Déploiement en échec', + 'web.repository.create': 'Dépôt créé', + 'web.repository.delete': 'Dépôt supprimé', + 'web.announce': 'Annonce publiée', + 'ticket.close': 'Ticket clôturé', +}; + +const describeEvent = (type) => EVENT_LABELS[type] ?? type; + +function botCard(bot) { + return card( + 'Bot', + { subtitle: bot.online ? `Connecté en tant que ${bot.username}` : 'Hors ligne' }, + grid( + stat('État', bot.online ? 'En ligne' : 'Hors ligne', { tone: bot.online ? 'success' : 'danger' }), + stat('Latence', bot.ping === null ? '—' : `${bot.ping} ms`), + stat('Actif depuis', formatDuration(bot.uptimeMs)), + stat('Commandes', bot.commands), + ), + h( + 'div', + { class: 'row advanced-only' }, + badge(`Node ${bot.nodeVersion}`), + badge(`discord.js ${bot.discordJsVersion}`), + badge(`${bot.memoryMb} Mo de mémoire`), + ), + ); +} + +function guildCard(guild) { + if (!guild) return card('Serveur Discord', {}, h('p', { class: 'empty', text: 'Serveur introuvable.' })); + + return card( + 'Serveur Discord', + { subtitle: guild.name }, + grid( + stat('Membres', guild.memberCount, { tone: 'primary' }), + stat('Salons', guild.channelCount), + stat('Rôles', guild.roleCount), + stat('Boosts', `Niveau ${guild.boostTier}`), + ), + ); +} + +function giteaCard(gitea) { + if (!gitea.configured) { + return card( + 'Organisation', + {}, + h('p', { class: 'empty', text: 'Gitea n’est pas configuré. Renseigne GITEA_URL et GITEA_TOKEN.' }), + ); + } + + return card( + 'Organisation', + { subtitle: gitea.organization?.fullName || gitea.organization?.name || '—' }, + grid( + stat('Dépôts', gitea.repositoryCount, { tone: 'primary' }), + stat('Issues ouvertes', gitea.openIssues, { tone: gitea.openIssues > 0 ? 'warning' : 'neutral' }), + stat('PR ouvertes', gitea.openPulls), + stat('Étoiles', gitea.stars), + ), + h('h3', { text: 'Dépôts récemment actifs' }), + table( + [ + { + label: 'Dépôt', + render: (repository) => + h('a', { href: `#/repos/${repository.fullName}`, text: repository.fullName }), + }, + { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 }, + { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 }, + { + label: 'Mise à jour', + className: 'nowrap', + render: (repository) => formatRelative(repository.updatedAt), + }, + ], + gitea.repositories, + { rowHref: (repository) => `#/repos/${repository.fullName}` }, + ), + ); +} + +function activityCard(activity) { + const deployTotals = Object.fromEntries(activity.deployments.map((row) => [row.status, row.count])); + + return card( + 'Activité', + {}, + grid( + stat('Tickets ouverts', activity.openTickets, { + tone: activity.openTickets > 0 ? 'warning' : 'neutral', + }), + stat('Sondages', activity.polls), + stat('Salons vocaux', activity.voiceChannels), + stat('Déploiements réussis', deployTotals.success ?? 0, { tone: 'success' }), + stat('Déploiements en échec', deployTotals.failed ?? 0, { + tone: deployTotals.failed ? 'danger' : 'neutral', + }), + ), + activity.environments.length > 0 && + h( + 'div', + { class: 'stack' }, + h('h3', { text: 'Dernier déploiement par environnement' }), + table( + [ + { label: 'Environnement', key: 'environment' }, + { label: 'Dépôt', key: 'repository' }, + { label: 'Version', render: (row) => row.release_tag ?? '—' }, + { label: 'État', render: (row) => badge(row.status, TONE[row.status] ?? 'neutral') }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.finished_at) }, + ], + activity.environments, + ), + ), + ); +} + +function systemCard(database, features) { + return card( + 'Système', + { advanced: true, subtitle: database.path }, + grid( + stat('Taille de la base', formatBytes(database.sizeBytes)), + stat('Migrations', database.migrations.length), + stat('Webhooks', features.webhooks ? 'Activés' : 'Désactivés', { + tone: features.webhooks ? 'success' : 'neutral', + }), + stat('Gitea', features.gitea ? 'Connecté' : 'Non configuré', { + tone: features.gitea ? 'success' : 'warning', + }), + ), + table( + [ + { label: 'Table', key: 'name' }, + { label: 'Lignes', className: 'num', key: 'count' }, + ], + Object.entries(database.tables) + .map(([name, count]) => ({ name, count })) + .sort((a, b) => b.count - a.count), + ), + ); +} + +export function render(host, { state }) { + autoRefresh(() => render(host, { state }), { + topics: ['tick', 'mutation', 'deployments', 'gitea', 'discord', 'community'], + }); + + return renderAsync( + host, + () => api.get('/api/overview'), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Vue d’ensemble' }), + h('p', { + class: 'muted', + text: `Bonjour ${state.me.displayName ?? ''} — voici l’état de FWS en un coup d’œil.`, + }), + ), + ), + botCard(data.bot), + guildCard(data.bot.guild), + giteaCard(data.gitea), + activityCard(data.activity), + systemCard(data.database, data.features), + card( + 'Derniers événements', + { advanced: true }, + table( + [ + { label: 'Événement', render: (event) => describeEvent(event.type) }, + { label: 'Type', className: 'advanced-only', key: 'type' }, + { label: 'Auteur', render: (event) => (event.actor_id ? `<@${event.actor_id}>` : '—') }, + { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) }, + ], + data.events, + ), + ), + ), + ); +} diff --git a/src/web/public/views/projects.js b/src/web/public/views/projects.js new file mode 100644 index 0000000..3db23a7 --- /dev/null +++ b/src/web/public/views/projects.js @@ -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); +} diff --git a/src/web/public/views/releases.js b/src/web/public/views/releases.js new file mode 100644 index 0000000..3a25b89 --- /dev/null +++ b/src/web/public/views/releases.js @@ -0,0 +1,338 @@ +import { api, encodeRepo } from '../core/api.js'; +import { formatRelative, h, mount, richText } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + spinner, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Publishing releases and watching the deployments they trigger (M16-T08). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +/** Suggests the next patch version from the last tag, so the field is never empty. */ +function nextTag(lastTag) { + const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(lastTag ?? ''); + if (!match) return 'v0.1.0'; + const [, major, minor, patch] = match; + const prefix = lastTag.startsWith('v') ? 'v' : ''; + return `${prefix}${major}.${minor}.${Number(patch) + 1}`; +} + +async function publishRelease(base, repository, releases, branches, reload) { + const tag = input({ value: nextTag(releases[0]?.tag) }); + const name = input({ placeholder: 'Nom de la version (facultatif)' }); + const targetBranch = select( + branches.map((branch) => ({ value: branch.name, label: branch.name })), + { value: repository.defaultBranch }, + ); + const body = textarea({ placeholder: 'Notes de version…' }); + let draft = false; + let prerelease = false; + let deploy = true; + + const generate = button( + 'Générer les notes depuis les commits', + async () => { + const result = await api.post(`${base}/releases/notes`, { target: targetBranch.value }); + body.value = result.notes; + toast(`${result.commitCount} commit(s) analysé(s) depuis ${result.previousTag ?? 'le début'}.`, 'info'); + }, + { tone: 'ghost' }, + ); + + const confirmed = await modal( + 'Publier une release', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Tag', tag, { help: 'SemVer, comme le CHANGELOG généré depuis les commits.' }), + field('Nom', name), + field('Branche cible', targetBranch), + generate, + field('Notes de version', body), + toggle(false, (checked) => (draft = checked), 'Brouillon (non publié, aucune notification)'), + toggle(false, (checked) => (prerelease = checked), 'Préversion'), + toggle(true, (checked) => (deploy = checked), 'Lancer les déploiements automatiques configurés'), + ), + submit: () => tag.value.trim() !== '', + }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post(`${base}/releases`, { + tag: tag.value.trim(), + name: name.value.trim() || undefined, + target: targetBranch.value, + body: body.value, + draft, + prerelease, + deploy, + }); + + const deployed = result.deployments ?? []; + toast( + deployed.length > 0 + ? `Release ${result.release.tag} publiée, ${deployed.length} déploiement(s) déclenché(s).` + : `Release ${result.release.tag} publiée.`, + 'success', + ); + reload(); +} + +/** Runs one of the repository's targets on a given version. */ +async function deployRelease(release, targets, reload) { + const runnable = targets.filter((target) => target.enabled); + if (runnable.length === 0) { + toast('Aucune cible active pour ce dépôt. Crée-en une depuis la page Déploiements.', 'error'); + return; + } + + const picker = select( + runnable.map((target) => ({ + value: String(target.id), + label: `${target.name} — ${target.environment}`, + })), + { value: String(runnable[0].id) }, + ); + const summary = h('p', { class: 'muted', text: runnable[0].summary }); + picker.addEventListener('change', () => { + summary.textContent = runnable.find((target) => String(target.id) === picker.value)?.summary ?? ''; + }); + + const confirmed = await modal( + `Déployer ${release.tag}`, + () => ({ + node: h('div', { class: 'stack' }, field('Cible', picker), summary), + submit: () => true, + }), + { confirmLabel: 'Déployer', tone: 'primary' }, + ); + if (!confirmed) return; + + toast('Déploiement lancé…', 'info'); + const result = await api.post(`/api/deploy/targets/${picker.value}/run`, { + releaseTag: release.tag, + ref: release.target || undefined, + }); + toast( + result.status === 'success' + ? `${release.tag} déployé.` + : `Déploiement en échec : ${result.error ?? 'raison inconnue'}`, + result.status === 'success' ? 'success' : 'error', + ); + reload(); +} + +function releaseRow(base, level, reload, targets) { + return [ + { + label: 'Version', + render: (release) => + h( + 'div', + {}, + h('a', { href: release.htmlUrl, target: '_blank', rel: 'noreferrer', text: release.tag }), + release.name && release.name !== release.tag && h('div', { class: 'muted', text: release.name }), + ), + }, + { + label: 'État', + render: (release) => + h( + 'div', + { class: 'row' }, + release.draft ? badge('Brouillon', 'neutral') : badge('Publiée', 'success'), + release.prerelease && badge('Préversion', 'warning'), + ), + }, + { label: 'Auteur', className: 'advanced-only', render: (release) => release.author ?? '—' }, + { + label: 'Publiée', + className: 'nowrap', + render: (release) => formatRelative(release.publishedAt ?? release.createdAt), + }, + { + label: '', + render: (release) => + h( + 'div', + { class: 'row' }, + button('Notes', () => showNotes(release), { tone: 'ghost' }), + level >= LEVELS.DEV && + !release.draft && + button('Déployer', () => deployRelease(release, targets, reload), { tone: 'primary' }), + level >= LEVELS.DEV && + release.draft && + button( + 'Publier', + async () => { + await api.patch(`${base}/releases/${release.id}`, { draft: false }); + toast('Release publiée.'); + reload(); + }, + { tone: 'success' }, + ), + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la release', `Supprimer ${release.tag} ?`))) return; + await api.delete(`${base}/releases/${release.id}`); + toast('Release supprimée.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ]; +} + +const showNotes = (release) => + modal(release.name || release.tag, () => ({ + node: richText(release.body || '_Aucune note._'), + submit: () => true, + })); + +export async function render(host, { state }) { + const level = state.me.accessLevel; + mount(host, spinner()); + + const params = new URLSearchParams(window.location.hash.split('?')[1] ?? ''); + const { repositories, configured } = await api.get('/api/repositories'); + + if (!configured || repositories.length === 0) { + mount(host, notice('Aucun dépôt Gitea accessible. Vérifie la configuration Gitea.', 'warning')); + return; + } + + const preferred = params.get('repo') || state.repository; + let current = repositories.find((item) => item.fullName === preferred) ?? repositories[0]; + + const picker = select( + repositories.map((item) => ({ value: item.fullName, label: item.fullName })), + { + value: current.fullName, + onChange: (event) => { + current = repositories.find((item) => item.fullName === event.target.value); + state.repository = current.fullName; + localStorage.setItem('fws.repository', current.fullName); + draw(); + }, + }, + ); + + const body = h('div', { class: 'stack' }); + + const draw = () => { + const base = `/api/repositories/${encodeRepo(current.fullName)}`; + renderAsync( + body, + async () => { + const [detail, releases, deployments, targets] = await Promise.all([ + api.get(base), + api.get(`${base}/releases`, { limit: 30 }), + api.get('/api/deployments', { repository: current.fullName, limit: 15 }), + api.get('/api/deploy/targets', { repository: current.fullName }).catch(() => ({ targets: [] })), + ]); + return { + detail, + releases: releases.releases, + deployments: deployments.deployments, + targets: targets.targets ?? [], + }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + card( + 'Releases', + { + subtitle: `${data.releases.length} version(s) sur ${current.fullName}`, + actions: + level >= LEVELS.DEV && + button( + 'Publier une release', + () => publishRelease(base, data.detail, data.releases, data.detail.branches, draw), + { tone: 'primary' }, + ), + }, + table(releaseRow(base, level, draw, data.targets), data.releases, { + empty: 'Aucune release publiée.', + }), + ), + + level >= LEVELS.DEV && + data.targets.length === 0 && + notice( + 'Aucune cible de déploiement pour ce dépôt : le bouton « Déployer » apparaîtra une fois une cible créée depuis la page Déploiements.', + 'info', + ), + + card( + 'Déploiements liés', + { subtitle: 'Déclenchés par la publication d’une version ou lancés à la main.' }, + table( + [ + { label: 'Cible', key: 'target_name' }, + { label: 'Environnement', key: 'environment' }, + { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' }, + { + label: 'État', + render: (row) => + badge( + row.status, + row.status === 'success' ? 'success' : row.status === 'failed' ? 'danger' : 'warning', + ), + }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) }, + ], + data.deployments, + { empty: 'Aucun déploiement pour ce dépôt.' }, + ), + ), + ), + ); + }; + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Releases' }), + h('p', { + class: 'muted', + text: 'Publie une version, génère ses notes depuis les commits et laisse les déploiements suivre.', + }), + ), + h('div', { style: { minWidth: '260px' } }, picker), + ), + body, + ), + ); + + draw(); +} diff --git a/src/web/public/views/repositories.js b/src/web/public/views/repositories.js new file mode 100644 index 0000000..ff3ef7a --- /dev/null +++ b/src/web/public/views/repositories.js @@ -0,0 +1,971 @@ +import { api, encodeRepo } from '../core/api.js'; +import { formatBytes, formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + confirmDangerous, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + spinner, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Repository list and the full management console of a single repository. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +// --- List ------------------------------------------------------------------- + +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( + 'a', + { class: 'repo-card', href: `#/repos/${repository.fullName}` }, + h('h3', { text: repository.name }), + h('p', { class: 'muted', text: repository.description || 'Sans description.' }), + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + repository.language && badge(repository.language, 'info'), + ), + h( + 'div', + { class: 'repo-meta' }, + h('span', { text: `${repository.openIssues ?? 0} issues` }), + h('span', { text: `${repository.openPulls ?? 0} PR` }), + h('span', { text: `${repository.releases ?? 0} releases` }), + h('span', { text: formatRelative(repository.updatedAt) }), + ), + ); +} + +function renderList(host) { + return renderAsync( + host, + () => api.get('/api/repositories'), + (data) => { + if (!data.configured) { + return notice( + 'Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN` dans les paramètres.', + 'warning', + ); + } + + const search = input({ placeholder: 'Filtrer par nom…', type: 'search' }); + const list = h('div', { class: 'repo-list' }); + + const draw = () => { + const needle = search.value.trim().toLowerCase(); + const filtered = data.repositories.filter( + (repository) => + needle === '' || + repository.name.toLowerCase().includes(needle) || + (repository.description ?? '').toLowerCase().includes(needle), + ); + mount( + list, + filtered.length > 0 + ? filtered.map(repositoryCard) + : h('p', { class: 'empty', text: 'Aucun dépôt ne correspond.' }), + ); + }; + search.addEventListener('input', draw); + draw(); + + return h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Dépôts' }), + h('p', { class: 'muted', text: `${data.repositories.length} dépôt(s) dans l’organisation.` }), + ), + h('div', { style: { minWidth: '240px' } }, search), + ), + list, + ); + }, + ); +} + +// --- Detail ----------------------------------------------------------------- + +const TABS = [ + { id: 'overview', label: 'Aperçu', level: LEVELS.STAFF }, + { id: 'issues', label: 'Issues', level: LEVELS.STAFF }, + { id: 'pulls', label: 'Pull requests', level: LEVELS.STAFF }, + { id: 'commits', label: 'Commits', level: LEVELS.STAFF }, + { id: 'branches', label: 'Branches', level: LEVELS.STAFF, advanced: true }, + { id: 'people', label: 'Collaborateurs', level: LEVELS.STAFF, advanced: true }, + { id: 'hooks', label: 'Webhooks', level: LEVELS.DEV, advanced: true }, + { id: 'actions', label: 'Actions', level: LEVELS.STAFF, advanced: true }, + { id: 'settings', label: 'Réglages', level: LEVELS.DEV }, +]; + +const issueBadge = (issue) => + issue.state === 'open' ? badge('Ouverte', 'success') : badge('Fermée', 'neutral'); + +function issuesTab(base, level) { + const host = h('div', { class: 'stack' }); + let stateFilter = 'open'; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/issues`, { state: stateFilter, limit: 50 }), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'row' }, + select( + [ + { value: 'open', label: 'Ouvertes' }, + { value: 'closed', label: 'Fermées' }, + { value: 'all', label: 'Toutes' }, + ], + { + value: stateFilter, + onChange: (event) => { + stateFilter = event.target.value; + load(); + }, + }, + ), + button('Nouvelle issue', () => createIssue(base, load), { tone: 'primary' }), + ), + table( + [ + { label: '#', className: 'num', key: 'number' }, + { + label: 'Titre', + render: (issue) => + h( + 'div', + {}, + h('a', { href: issue.htmlUrl, target: '_blank', rel: 'noreferrer', text: issue.title }), + issue.labels.length > 0 && + h( + 'div', + { class: 'row' }, + issue.labels.map((label) => badge(label.name, 'info')), + ), + ), + }, + { label: 'État', render: issueBadge }, + { label: 'Auteur', render: (issue) => issue.author ?? '—' }, + { label: 'Maj', className: 'nowrap', render: (issue) => formatRelative(issue.updatedAt) }, + { + label: '', + render: (issue) => + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + issue.state === 'open' ? 'Fermer' : 'Rouvrir', + async () => { + await api.patch(`${base}/issues/${issue.number}`, { + state: issue.state === 'open' ? 'closed' : 'open', + }); + toast('Issue mise à jour.'); + load(); + }, + { tone: 'ghost' }, + ), + button('Commenter', () => commentIssue(base, issue, load), { tone: 'ghost' }), + ), + }, + ], + data.issues, + { empty: 'Aucune issue.' }, + ), + ), + ); + + load(); + return host; +} + +async function createIssue(base, reload) { + const title = input({ placeholder: 'Titre clair et actionnable' }); + const body = textarea({ placeholder: 'Contexte, étapes de reproduction, comportement attendu…' }); + + const confirmed = await modal( + 'Nouvelle issue', + () => ({ + node: h('div', { class: 'stack' }, field('Titre', title), field('Description', body)), + submit: () => title.value.trim().length >= 3, + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const issue = await api.post(`${base}/issues`, { title: title.value.trim(), body: body.value }); + toast(`Issue #${issue.number} créée.`); + reload(); +} + +async function commentIssue(base, issue, reload) { + const body = textarea({ placeholder: 'Ton commentaire…' }); + const confirmed = await modal( + `Commenter #${issue.number}`, + () => ({ node: field('Commentaire', body), submit: () => body.value.trim() !== '' }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post(`${base}/issues/${issue.number}/comments`, { body: body.value }); + toast('Commentaire publié.'); + reload(); +} + +function pullsTab(base, level) { + const host = h('div', { class: 'stack' }); + let stateFilter = 'open'; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/pulls`, { state: stateFilter, limit: 50 }), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'row' }, + select( + [ + { value: 'open', label: 'Ouvertes' }, + { value: 'closed', label: 'Fermées' }, + { value: 'all', label: 'Toutes' }, + ], + { + value: stateFilter, + onChange: (event) => { + stateFilter = event.target.value; + load(); + }, + }, + ), + level >= LEVELS.DEV && button('Nouvelle PR', () => createPull(base, load), { tone: 'primary' }), + ), + table( + [ + { label: '#', className: 'num', key: 'number' }, + { + label: 'Titre', + render: (pull) => + h('a', { href: pull.htmlUrl, target: '_blank', rel: 'noreferrer', text: pull.title }), + }, + { + label: 'Branches', + className: 'nowrap advanced-only', + render: (pull) => `${pull.head} → ${pull.base}`, + }, + { + label: 'État', + render: (pull) => + pull.merged + ? badge('Mergée', 'info') + : pull.draft + ? badge('Brouillon', 'neutral') + : issueBadge(pull), + }, + { label: 'Auteur', render: (pull) => pull.author ?? '—' }, + { label: 'Maj', className: 'nowrap', render: (pull) => formatRelative(pull.updatedAt) }, + { + label: '', + render: (pull) => + level >= LEVELS.DEV && + !pull.merged && + pull.state === 'open' && + button('Merger', () => mergePull(base, pull, load), { tone: 'success' }), + }, + ], + data.pulls, + { empty: 'Aucune pull request.' }, + ), + ), + ); + + load(); + return host; +} + +async function createPull(base, reload) { + const title = input({ placeholder: 'feat(scope): description' }); + const head = input({ placeholder: 'feat/ma-branche' }); + const baseBranch = input({ value: 'main' }); + const body = textarea({ placeholder: 'Ce que fait la PR et pourquoi.' }); + + const confirmed = await modal( + 'Nouvelle pull request', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Titre', title, { help: 'Format Conventional Commits, comme les commits FWS.' }), + field('Branche source', head), + field('Branche cible', baseBranch), + field('Description', body), + ), + submit: () => title.value.trim() !== '' && head.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const pull = await api.post(`${base}/pulls`, { + title: title.value.trim(), + head: head.value.trim(), + base: baseBranch.value.trim(), + body: body.value, + }); + toast(`PR #${pull.number} créée.`); + reload(); +} + +async function mergePull(base, pull, reload) { + const style = select( + [ + { value: 'squash', label: 'Squash (convention FWS)' }, + { value: 'merge', label: 'Merge commit' }, + { value: 'rebase', label: 'Rebase' }, + ], + { value: 'squash' }, + ); + let deleteBranch = true; + + const confirmed = await modal( + `Merger #${pull.number}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', { text: `${pull.head} → ${pull.base}` }), + field('Méthode', style), + toggle(true, (checked) => (deleteBranch = checked), 'Supprimer la branche après le merge'), + ), + submit: () => true, + }), + { confirmLabel: 'Merger', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post(`${base}/pulls/${pull.number}/merge`, { style: style.value, deleteBranch }); + toast('Pull request mergée.'); + reload(); +} + +function commitsTab(base, branches) { + const host = h('div', { class: 'stack' }); + let branch = ''; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/commits`, { branch, limit: 40 }), + (data) => + h( + 'div', + { class: 'stack' }, + select( + [ + { value: '', label: 'Branche par défaut' }, + ...branches.map((item) => ({ value: item.name, label: item.name })), + ], + { + value: branch, + onChange: (event) => { + branch = event.target.value; + load(); + }, + }, + ), + table( + [ + { + label: 'Commit', + render: (commit) => + h('a', { + href: commit.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: commit.shortSha, + }), + }, + { label: 'Message', key: 'message' }, + { label: 'Auteur', render: (commit) => commit.authorLogin || commit.author || '—' }, + { label: 'Date', className: 'nowrap', render: (commit) => formatRelative(commit.date) }, + ], + data.commits, + { empty: 'Aucun commit.' }, + ), + ), + ); + + load(); + return host; +} + +function branchesTab(base, repository, level, refresh) { + return h( + 'div', + { class: 'stack' }, + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + 'Nouvelle branche', + async () => { + const name = input({ placeholder: 'feat/ma-branche' }); + const from = input({ value: repository.defaultBranch ?? 'main' }); + const confirmed = await modal( + 'Créer une branche', + () => ({ + node: h('div', { class: 'stack' }, field('Nom', name), field('Depuis', from)), + submit: () => name.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + await api.post(`${base}/branches`, { name: name.value.trim(), from: from.value.trim() }); + toast('Branche créée.'); + refresh(); + }, + { tone: 'primary' }, + ), + ), + table( + [ + { + label: 'Branche', + render: (branch) => + h( + 'div', + { class: 'row' }, + h('strong', { text: branch.name }), + branch.name === repository.defaultBranch && badge('Par défaut', 'info'), + branch.protected && badge('Protégée', 'warning'), + ), + }, + { label: 'Dernier commit', render: (branch) => branch.commitMessage || '—' }, + { label: 'SHA', className: 'nowrap', render: (branch) => branch.commit ?? '—' }, + { label: 'Date', className: 'nowrap', render: (branch) => formatRelative(branch.commitAt) }, + { + label: '', + render: (branch) => + level >= LEVELS.DEV && + branch.name !== repository.defaultBranch && + !branch.protected && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la branche', `Supprimer « ${branch.name} » ?`))) return; + await api.delete(`${base}/branches`, { name: branch.name }); + toast('Branche supprimée.'); + refresh(); + }, + { tone: 'danger' }, + ), + }, + ], + repository.branches, + ), + ); +} + +function peopleTab(base, repository, level, refresh) { + return h( + 'div', + { class: 'stack' }, + level >= LEVELS.OWNER && + button( + 'Ajouter un collaborateur', + async () => { + const login = input({ placeholder: 'identifiant Gitea' }); + const permission = select( + [ + { value: 'read', label: 'Lecture' }, + { value: 'write', label: 'Écriture' }, + { value: 'admin', label: 'Administration' }, + ], + { value: 'write' }, + ); + const confirmed = await modal( + 'Ajouter un collaborateur', + () => ({ + node: h('div', { class: 'stack' }, field('Compte', login), field('Permission', permission)), + submit: () => login.value.trim() !== '', + }), + { confirmLabel: 'Ajouter', tone: 'primary' }, + ); + if (!confirmed) return; + await api.put(`${base}/collaborators/${encodeURIComponent(login.value.trim())}`, { + permission: permission.value, + }); + toast('Collaborateur ajouté.'); + refresh(); + }, + { tone: 'primary' }, + ), + table( + [ + { + label: 'Compte', + render: (user) => + h( + 'div', + { class: 'row' }, + user.avatar && + h('img', { + src: user.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: user.login }), + ), + }, + { label: 'Nom', render: (user) => user.fullName || '—' }, + { + label: 'Droits', + render: (user) => + h( + 'div', + { class: 'row' }, + user.permissions?.admin && badge('Admin', 'danger'), + user.permissions?.push && badge('Écriture', 'info'), + user.permissions?.pull && badge('Lecture', 'neutral'), + ), + }, + { + label: '', + render: (user) => + level >= LEVELS.OWNER && + button( + 'Retirer', + async () => { + if (!(await confirmAction('Retirer le collaborateur', `Retirer ${user.login} du dépôt ?`))) + return; + await api.delete(`${base}/collaborators/${encodeURIComponent(user.login)}`); + toast('Collaborateur retiré.'); + refresh(); + }, + { tone: 'danger' }, + ), + }, + ], + repository.collaborators, + ), + ); +} + +function hooksTab(base, level) { + const host = h('div', { class: 'stack' }); + + const load = () => + renderAsync( + host, + () => api.get(`${base}/hooks`), + (data) => + h( + 'div', + { class: 'stack' }, + notice( + 'Un webhook permet à Gitea de prévenir le bot en temps réel (issues, PR, commits, releases).', + 'info', + ), + level >= LEVELS.OWNER && + button( + 'Brancher ce dépôt sur le bot', + async () => { + if ( + !(await confirmAction( + 'Créer le webhook', + 'Gitea sera configuré pour envoyer les événements à ce bot, avec le secret déjà en place.', + )) + ) { + return; + } + const hook = await api.post(`${base}/hooks`, {}); + toast(`Webhook créé vers ${hook.url}.`); + load(); + }, + { tone: 'primary' }, + ), + table( + [ + { label: 'URL', key: 'url' }, + { label: 'Événements', render: (hook) => (hook.events ?? []).join(', ') }, + { + label: 'Actif', + render: (hook) => (hook.active ? badge('Oui', 'success') : badge('Non', 'neutral')), + }, + { + label: '', + render: (hook) => + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le webhook', hook.url))) return; + await api.delete(`${base}/hooks/${hook.id}`); + toast('Webhook supprimé.'); + load(); + }, + { tone: 'danger' }, + ), + }, + ], + data.hooks, + { empty: 'Aucun webhook sur ce dépôt.' }, + ), + ), + ); + + load(); + return host; +} + +function actionsTab(base) { + const host = h('div', {}); + renderAsync( + host, + () => api.get(`${base}/actions`), + (data) => + data.available + ? table( + [ + { label: 'Workflow', key: 'name' }, + { label: 'Branche', key: 'headBranch' }, + { label: 'Commit', key: 'headSha' }, + { + label: 'État', + render: (task) => + badge( + task.conclusion ?? task.status ?? '—', + task.conclusion === 'success' + ? 'success' + : task.conclusion === 'failure' + ? 'danger' + : 'warning', + ), + }, + { label: 'Quand', className: 'nowrap', render: (task) => formatRelative(task.createdAt) }, + ], + data.tasks, + { empty: 'Aucune exécution.' }, + ) + : notice('Gitea Actions n’est pas disponible sur ce dépôt ou cette version de Gitea.', 'info'), + ); + return host; +} + +function settingsTab(base, repository, level, refresh) { + if (level < LEVELS.DEV) return notice('Réservé aux niveaux Dev et Owner.', 'warning'); + + const description = input({ value: repository.description ?? '' }); + const website = input({ value: repository.website ?? '' }); + const defaultBranch = select( + repository.branches.map((branch) => ({ value: branch.name, label: branch.name })), + { value: repository.defaultBranch }, + ); + + const switches = [ + ['has_issues', 'Issues activées', repository.hasIssues], + ['has_pull_requests', 'Pull requests activées', repository.hasPullRequests], + ['has_releases', 'Releases activées', repository.hasReleases], + ['has_wiki', 'Wiki activé', repository.hasWiki], + ['has_actions', 'Gitea Actions activées', repository.hasActions], + ['allow_squash_merge', 'Autoriser le squash merge', repository.allowSquash], + ['allow_merge_commits', 'Autoriser le merge commit', repository.allowMergeCommits], + ['allow_rebase', 'Autoriser le rebase', repository.allowRebase], + ['private', 'Dépôt privé', repository.private], + ['archived', 'Dépôt archivé (lecture seule)', repository.archived], + ]; + const values = Object.fromEntries(switches.map(([key, , value]) => [key, value])); + + return h( + 'div', + { class: 'stack' }, + card( + 'Identité', + { + actions: button( + 'Enregistrer', + async () => { + await api.patch(base, { + description: description.value, + website: website.value, + default_branch: defaultBranch.value, + }); + toast('Dépôt mis à jour.'); + refresh(); + }, + { tone: 'primary' }, + ), + }, + field('Description', description), + field('Site web', website), + field('Branche par défaut', defaultBranch), + ), + + card( + 'Fonctionnalités', + { + actions: button( + 'Appliquer', + async () => { + await api.patch(base, values); + toast('Réglages appliqués.'); + refresh(); + }, + { tone: 'primary' }, + ), + }, + ...switches.map(([key, label, value]) => + toggle(Boolean(value), (checked) => (values[key] = checked), label), + ), + ), + + level >= LEVELS.OWNER && + card( + 'Zone de danger', + { subtitle: 'Ces actions sont irréversibles.' }, + notice( + 'La suppression efface le dépôt, ses issues, ses PR et ses releases sur Gitea. Il n’y a pas de corbeille.', + 'error', + ), + button( + 'Supprimer ce dépôt', + async () => { + const ok = await confirmDangerous( + 'Supprimer le dépôt', + `Le dépôt ${repository.fullName} et tout son contenu seront définitivement supprimés.`, + repository.fullName, + ); + if (!ok) return; + await api.delete(base, { confirm: repository.fullName }); + toast('Dépôt supprimé.'); + window.location.hash = '#/repos'; + }, + { tone: 'danger' }, + ), + ), + ); +} + +function overviewTab(repository) { + const languages = Object.entries(repository.languages ?? {}); + const total = languages.reduce((sum, [, bytes]) => sum + bytes, 0) || 1; + + return h( + 'div', + { class: 'stack' }, + card( + 'Chiffres', + {}, + grid( + stat('Issues ouvertes', repository.openIssues, { + tone: repository.openIssues > 0 ? 'warning' : 'neutral', + }), + stat('PR ouvertes', repository.openPulls), + stat('Releases', repository.releases), + stat('Branches', repository.branches.length), + stat('Étoiles', repository.stars), + stat('Taille', formatBytes((repository.sizeKb ?? 0) * 1024)), + ), + ), + + repository.latestRelease && + card( + 'Dernière release', + { + actions: h('a', { + class: 'btn btn-ghost', + href: repository.latestRelease.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: '↗ Voir', + }), + }, + h( + 'p', + {}, + h('strong', { text: repository.latestRelease.tag }), + ' — ', + repository.latestRelease.name ?? '', + ), + h('p', { class: 'muted', text: `Publiée ${formatRelative(repository.latestRelease.publishedAt)}` }), + ), + + languages.length > 0 && + card( + 'Langages', + { advanced: true }, + ...languages + .sort((a, b) => b[1] - a[1]) + .map(([name, bytes]) => + h( + 'div', + {}, + h( + 'div', + { class: 'row', style: { justifyContent: 'space-between' } }, + h('span', { text: name }), + h('span', { class: 'muted', text: `${((bytes / total) * 100).toFixed(1)} %` }), + ), + h('div', { class: 'bar' }, h('span', { style: { width: `${(bytes / total) * 100}%` } })), + ), + ), + ), + + repository.topics.length > 0 && + card( + 'Sujets', + { advanced: true }, + h( + 'div', + { class: 'row' }, + repository.topics.map((topic) => badge(topic, 'info')), + ), + ), + + card( + 'Cloner', + { advanced: true }, + h('pre', {}, h('code', { text: `git clone ${repository.cloneUrl}` })), + repository.sshUrl && h('pre', {}, h('code', { text: `git clone ${repository.sshUrl}` })), + ), + ); +} + +async function renderDetail(host, state, owner, name) { + const base = `/api/repositories/${encodeRepo(`${owner}/${name}`)}`; + const level = state.me.accessLevel; + mount(host, spinner()); + + let repository; + try { + repository = await api.get(base); + } catch (error) { + mount(host, notice(error.message, 'error')); + return; + } + + const refresh = () => renderDetail(host, state, owner, name); + const body = h('div', { class: 'stack' }); + const tabs = TABS.filter((tab) => level >= tab.level && (!tab.advanced || state.mode === 'advanced')); + let active = tabs[0].id; + + const drawTab = () => { + const content = { + overview: () => overviewTab(repository), + issues: () => issuesTab(base, level), + pulls: () => pullsTab(base, level), + commits: () => commitsTab(base, repository.branches), + branches: () => branchesTab(base, repository, level, refresh), + people: () => peopleTab(base, repository, level, refresh), + hooks: () => hooksTab(base, level), + actions: () => actionsTab(base), + settings: () => settingsTab(base, repository, level, refresh), + }; + mount(body, content[active]()); + for (const control of tabBar.querySelectorAll('button')) { + control.classList.toggle('active', control.dataset.tab === active); + } + }; + + const tabBar = h( + 'div', + { class: 'tabs' }, + tabs.map((tab) => + h('button', { + type: 'button', + text: tab.label, + dataset: { tab: tab.id }, + onClick: () => { + active = tab.id; + drawTab(); + }, + }), + ), + ); + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('p', { class: 'muted' }, h('a', { href: '#/repos', text: '← Tous les dépôts' })), + h('h1', { text: repository.fullName }), + h('p', { class: 'muted', text: repository.description || 'Sans description.' }), + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + badge(`Branche ${repository.defaultBranch}`, 'info'), + ), + ), + h( + 'div', + { class: 'row' }, + h('a', { + class: 'btn btn-ghost', + href: repository.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: '↗ Gitea', + }), + h('a', { + class: 'btn btn-ghost', + href: `#/releases?repo=${repository.fullName}`, + text: 'Releases', + }), + ), + ), + repository.archived && notice('Ce dépôt est archivé : Gitea refusera toute écriture.', 'warning'), + tabBar, + body, + ), + ); + + drawTab(); +} + +export function render(host, { params, state }) { + if (params.length >= 2) return renderDetail(host, state, params[0], params[1]); + return renderList(host); +} diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js new file mode 100644 index 0000000..e1dd973 --- /dev/null +++ b/src/web/public/views/settings.js @@ -0,0 +1,542 @@ +import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; +import { formatDate, formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + confirmDangerous, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + stat, + table, + toast, + toggle, +} from '../core/ui.js'; + +/** Settings tab: every knob the dashboard exposes, grouped by concern (M16-T10). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const keyValue = (rows) => + table( + [ + { label: 'Réglage', key: 'label' }, + { label: 'Valeur', render: (row) => row.value ?? '—' }, + ], + rows, + ); + +/** One control per setting, typed after its declaration. */ +function settingControl(setting, value, apply) { + if (setting.type === 'bool') { + return h( + 'div', + {}, + toggle(Boolean(value), apply, setting.label), + h('div', { class: 'field-help', text: setting.help }), + ); + } + + if (setting.type === 'enum' && Array.isArray(setting.options)) { + return field( + setting.label, + select( + setting.options.map((option) => ({ value: option, label: option })), + { value, onChange: (event) => apply(event.target.value) }, + ), + { 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 { + 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; + }), + ); + }), + editable && button('Recharger les réglages', reload, { tone: 'ghost' }), + ); +} + +const testButton = (service, label) => + button( + label, + async () => { + const result = await api.post(`/api/settings/test/${service}`, {}); + toast(result.detail, result.ok ? 'success' : 'error'); + }, + { tone: 'ghost' }, + ); + +function connectionsCard(raw) { + const data = { + discord: raw.discord ?? {}, + gitea: raw.gitea ?? {}, + webhook: raw.webhook ?? {}, + web: raw.web ?? {}, + }; + return h( + 'div', + { class: 'stack' }, + card( + 'Discord', + { actions: testButton('discord', 'Tester la connexion') }, + grid( + stat('Token', data.discord.tokenConfigured ? 'Configuré' : 'Manquant', { + tone: data.discord.tokenConfigured ? 'success' : 'danger', + }), + stat('Application ID', data.discord.clientId || '—'), + stat('Serveur', data.discord.guildId || '—'), + ), + h('h3', { class: 'advanced-only', text: 'Rôles FWS' }), + h( + 'div', + { class: 'advanced-only' }, + keyValue(Object.entries(data.discord.roles ?? {}).map(([label, value]) => ({ label, value }))), + ), + h('h3', { class: 'advanced-only', text: 'Salons' }), + h( + 'div', + { class: 'advanced-only' }, + keyValue(Object.entries(data.discord.channels ?? {}).map(([label, value]) => ({ label, value }))), + ), + ), + + card( + 'Gitea', + { actions: testButton('gitea', 'Tester le jeton') }, + grid( + stat('Instance', data.gitea.url || '—'), + stat('Organisation', data.gitea.owner || '—'), + stat('Dépôt principal', data.gitea.repo || '—'), + stat('Jeton', data.gitea.tokenConfigured ? 'Configuré' : 'Manquant', { + tone: data.gitea.tokenConfigured ? 'success' : 'warning', + }), + ), + h( + 'div', + { class: 'row advanced-only' }, + badge(`Délai ${data.gitea.timeoutMs} ms`), + badge(`${data.gitea.maxRetries} tentative(s) de secours`), + ), + ), + + card( + 'Webhooks Gitea', + {}, + grid( + stat('État', data.webhook.enabled ? 'Activés' : 'Désactivés', { + tone: data.webhook.enabled ? 'success' : 'neutral', + }), + stat('Secret', data.webhook.secretConfigured ? 'Configuré' : 'Manquant', { + tone: data.webhook.secretConfigured ? 'success' : 'warning', + }), + stat('Port', data.webhook.port), + ), + data.webhook.publicUrl && + h( + 'div', + {}, + h('p', { class: 'muted', text: 'URL à renseigner dans Gitea → Paramètres → Webhooks :' }), + h('pre', {}, h('code', { text: data.webhook.publicUrl })), + ), + data.webhook.enabled && + !data.webhook.secretConfigured && + notice('Les webhooks sont activés sans secret : tous les événements seront rejetés.', 'error'), + ), + + card( + 'Tableau de bord', + { advanced: true }, + grid( + stat('Écoute', `${data.web.host}:${data.web.port}`), + stat('URL publique', data.web.publicUrl || '—'), + stat('Connexion Discord', data.web.oauthConfigured ? 'Prête' : 'Non configurée', { + tone: data.web.oauthConfigured ? 'success' : 'warning', + }), + stat('Durée de session', `${data.web.sessionTtlHours} h`), + ), + h( + 'div', + {}, + h('p', { class: 'muted', text: 'URL de redirection à déclarer dans le Developer Portal :' }), + h('pre', {}, h('code', { text: data.web.redirectUri })), + ), + h( + 'div', + { class: 'row' }, + badge( + data.web.allowCommandDeploys ? 'Déploiements shell autorisés' : 'Déploiements shell bloqués', + data.web.allowCommandDeploys ? 'warning' : 'neutral', + ), + badge(data.web.allowRestart ? 'Redémarrage autorisé' : 'Redémarrage bloqué', 'neutral'), + badge(`${data.web.rateLimitPerMinute} req/min`, 'neutral'), + ), + ), + ); +} + +function sessionsCard(reload) { + const host = h('div', {}); + renderAsync( + host, + () => api.get('/api/settings/sessions'), + (data) => + table( + [ + { + label: 'Personne', + render: (session) => + h( + 'div', + { class: 'row' }, + session.avatar && + h('img', { + src: session.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: session.display_name ?? session.username ?? '—' }), + session.current && badge('Cette session', 'info'), + ), + }, + { label: 'Niveau', render: (session) => badge(session.accessLabel, 'neutral') }, + { label: 'Origine', key: 'source' }, + { label: 'IP', className: 'advanced-only', key: 'ip' }, + { + label: 'Dernière activité', + className: 'nowrap', + render: (session) => formatRelative(session.last_seen_at), + }, + { + label: 'Expire', + className: 'nowrap advanced-only', + render: (session) => formatDate(session.expires_at), + }, + { + label: '', + render: (session) => + !session.current && + button( + 'Révoquer', + async () => { + if (!(await confirmAction('Révoquer la session', 'Cette personne devra se reconnecter.'))) + return; + await api.delete(`/api/settings/sessions/${session.id}`); + toast('Session révoquée.'); + reload(); + }, + { tone: 'danger' }, + ), + }, + ], + data.sessions, + { empty: 'Aucune session active.' }, + ), + ); + return card('Sessions ouvertes', { subtitle: 'Qui est connecté au tableau de bord en ce moment.' }, host); +} + +function tokensCard(reload) { + const host = h('div', {}); + + const load = () => + renderAsync( + host, + () => api.get('/api/settings/tokens'), + (data) => + table( + [ + { label: 'Nom', key: 'name' }, + { label: 'Préfixe', className: 'nowrap', key: 'prefix' }, + { label: 'Niveau', render: (token) => badge(token.accessLabel, 'neutral') }, + { label: 'Créé', className: 'nowrap', render: (token) => formatRelative(token.created_at) }, + { + label: 'Dernier usage', + className: 'nowrap', + render: (token) => (token.last_used_at ? formatRelative(token.last_used_at) : 'jamais'), + }, + { + label: 'État', + render: (token) => (token.active ? badge('Actif', 'success') : badge('Révoqué', 'neutral')), + }, + { + label: '', + render: (token) => + token.active && + button( + 'Révoquer', + async () => { + if (!(await confirmAction('Révoquer le jeton', token.name))) return; + await api.delete(`/api/settings/tokens/${token.id}`); + toast('Jeton révoqué.'); + load(); + }, + { tone: 'danger' }, + ), + }, + ], + data.tokens, + { empty: 'Aucun jeton d’API.' }, + ), + ); + + load(); + + return card( + 'Jetons d’API', + { + subtitle: 'Pour appeler cette API depuis un script ou une CI, sans compte Discord.', + actions: button( + 'Créer un jeton', + async () => { + const name = input({ placeholder: 'ci-deploiement' }); + const level = select( + [ + { value: '1', label: 'Staff — lecture' }, + { value: '2', label: 'Dev — écriture' }, + { value: '3', label: 'Owner — tout' }, + ], + { value: '1' }, + ); + const confirmed = await modal( + 'Nouveau jeton d’API', + () => ({ + node: h('div', { class: 'stack' }, field('Nom', name), field('Niveau d’accès', level)), + submit: () => name.value.trim().length >= 3, + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/settings/tokens', { + name: name.value.trim(), + accessLevel: Number(level.value), + }); + await modal( + 'Jeton créé', + () => ({ + node: h( + 'div', + { class: 'stack' }, + notice('Copie ce jeton maintenant : il ne sera plus jamais affiché.', 'warning'), + h('pre', {}, h('code', { text: result.token })), + h('p', { class: 'muted', text: 'À envoyer en en-tête `Authorization: Bearer `.' }), + ), + submit: () => true, + }), + { confirmLabel: 'J’ai copié' }, + ); + load(); + reload(); + }, + { tone: 'primary' }, + ), + }, + host, + ); +} + +function maintenanceCard(data) { + const runtime = data.runtime ?? {}; + return card( + 'Maintenance', + { subtitle: `Base : ${runtime.databasePath ?? '—'}` }, + grid( + stat('Environnement', runtime.nodeEnv), + stat('Niveau de log', runtime.logLevel), + stat('Rétention', `${runtime.logRetentionDays ?? '—'} jours`), + stat('PID', runtime.pid), + ), + h( + 'div', + { class: 'row' }, + button( + 'Sauvegarder la base', + async () => { + const result = await api.post('/api/settings/backup', {}); + toast(`Sauvegarde écrite : ${result.file}`); + }, + { tone: 'primary' }, + ), + button( + 'Purger les anciens événements', + async () => { + const result = await api.post('/api/settings/purge', {}); + toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`); + }, + { tone: 'ghost' }, + ), + data.web?.allowRestart && + button( + 'Redémarrer le bot', + async () => { + const ok = await confirmDangerous( + 'Redémarrer le bot', + 'Le processus va s’arrêter. Sans superviseur (systemd, pm2, Docker), il ne redémarrera pas tout seul.', + 'redemarrer', + ); + if (!ok) return; + await api.post('/api/settings/restart', {}); + toast('Redémarrage demandé.', 'info'); + }, + { tone: 'danger' }, + ), + ), + !data.web?.allowRestart && + h('p', { class: 'muted', text: 'Le redémarrage depuis le site est désactivé (`WEB_ALLOW_RESTART`).' }), + ); +} + +function referenceCard(data) { + const reference = data.reference ?? {}; + return card( + 'Référence', + { advanced: true, subtitle: 'Ce que le bot connaît, pour se repérer.' }, + h('h3', { text: 'Niveaux d’accès' }), + table( + [ + { label: 'Nom', key: 'name' }, + { label: 'Valeur', className: 'num', key: 'value' }, + { label: 'Libellé Discord', key: 'label' }, + ], + reference.accessLevels ?? [], + ), + h('h3', { text: 'Catégories de tickets' }), + table( + [ + { label: 'Identifiant', key: 'id' }, + { label: 'Libellé', key: 'label' }, + { label: 'Visible par', render: (category) => category.scope.join(', ') }, + ], + reference.ticketCategories ?? [], + ), + h('h3', { text: 'Types de notification' }), + h( + 'div', + { class: 'row' }, + (reference.notificationTypes ?? []).map((type) => badge(type, 'info')), + ), + ); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + autoRefresh(reload, { topics: ['settings'] }); + + return renderAsync( + host, + () => api.get('/api/settings'), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Paramètres' }), + h('p', { + class: 'muted', + text: 'Les réglages du bot, ses connexions et la sécurité du tableau de bord.', + }), + ), + level >= LEVELS.OWNER && + h('a', { + class: 'btn btn-primary', + href: '#/setup', + text: 'Assistant de configuration .env', + }), + ), + + level >= LEVELS.OWNER && + notice( + 'Les valeurs du fichier .env ne sont lues qu’au démarrage. L’assistant les modifie, un redémarrage les applique.', + 'info', + ), + + behaviourCard(data, level, reload), + connectionsCard(data), + level >= LEVELS.OWNER ? sessionsCard(reload) : null, + level >= LEVELS.OWNER ? tokensCard(reload) : null, + level >= LEVELS.OWNER ? maintenanceCard(data) : null, + referenceCard(data), + ), + ); +} diff --git a/src/web/public/views/setup.js b/src/web/public/views/setup.js new file mode 100644 index 0000000..3014c9f --- /dev/null +++ b/src/web/public/views/setup.js @@ -0,0 +1,394 @@ +import { api } from '../core/api.js'; +import { h, mount, richText } from '../core/dom.js'; +import { button, card, field, input, notice, select, spinner, toast, toggle } from '../core/ui.js'; + +/** + * Step by step `.env` wizard (M16-T09). + * + * Walks through one section at a time: what the section is for, how to obtain + * each value, then the fields themselves with live validation. Nothing is + * written until « Enregistrer » is pressed, and the previous file is backed up. + */ + +const stateOf = (data) => ({ + data, + /** Only the fields the user actually touched. */ + edits: {}, + step: 0, + showAdvanced: false, + errors: { ...data.errors }, + warnings: [...data.warnings], + missing: [...data.missingRequired], + diff: [], + lastSave: null, +}); + +const valueOf = (view, key) => view.edits[key] ?? view.data.values[key] ?? ''; + +/** Step texts reference other fields, so they always show the values being typed. */ +const fillPlaceholders = (view, text) => + text + .replaceAll('{WEB_PUBLIC_URL}', valueOf(view, 'WEB_PUBLIC_URL') || 'https://ton-domaine') + .replaceAll('{WEBHOOK_PATH}', valueOf(view, 'WEBHOOK_PATH') || '/webhooks/gitea'); + +/** A section is complete when none of its variables is in error or missing. */ +function sectionStatus(view, sectionId) { + const variables = view.data.variables.filter((variable) => variable.section === sectionId); + const invalid = variables.some((variable) => view.errors[variable.key]); + const missing = variables.some((variable) => view.missing.includes(variable.key)); + const filled = variables.some((variable) => { + const value = valueOf(view, variable.key); + return value !== '' || view.data.secrets[variable.key]; + }); + return { invalid, missing, filled }; +} + +export async function render(host, { standalone = false } = {}) { + mount(host, spinner('Lecture de la configuration…')); + + const data = await api.get('/api/configuration'); + const view = stateOf(data); + const container = standalone + ? h('div', { class: 'main', style: { maxWidth: '1100px', margin: '0 auto' } }) + : h('div', {}); + mount(host, container); + + let validateTimer = null; + const scheduleValidation = () => { + clearTimeout(validateTimer); + validateTimer = setTimeout(async () => { + const result = await api.post('/api/configuration/validate', { values: view.edits }).catch(() => null); + if (!result) return; + view.errors = result.errors; + view.warnings = result.warnings; + view.missing = result.missingRequired; + view.diff = result.diff; + draw(); + }, 350); + }; + + const setValue = (key, value) => { + view.edits[key] = value; + scheduleValidation(); + }; + + function controlFor(variable) { + const key = variable.key; + const current = valueOf(view, key); + + if (variable.type === 'bool') { + return toggle(current === 'true', (checked) => { + setValue(key, checked ? 'true' : 'false'); + draw(); + }); + } + + if (variable.type === 'enum') { + return select( + variable.options.map((option) => ({ value: option, label: option })), + { value: current, onChange: (event) => setValue(key, event.target.value) }, + ); + } + + const control = input({ + type: variable.type === 'secret' ? 'password' : 'text', + value: current, + placeholder: variable.placeholder ?? variable.default ?? '', + autocomplete: 'off', + spellcheck: 'false', + onInput: (event) => setValue(key, event.target.value), + }); + + if (variable.type !== 'secret' && !variable.generator && !variable.testable) return control; + + const extras = [control]; + if (variable.generator) { + extras.push( + button( + 'Générer', + async () => { + const { value } = await api.post('/api/configuration/generate', { kind: variable.generator }); + control.value = value; + setValue(key, value); + toast('Secret généré. Il ne sera visible qu’ici.', 'info'); + }, + { tone: 'ghost' }, + ), + ); + } + if (variable.testable) { + extras.push( + button( + 'Tester', + async () => { + const result = await api.post(`/api/configuration/test/${variable.testable}`, { + values: view.edits, + }); + toast(result.detail, result.ok ? (result.warning ? 'info' : 'success') : 'error'); + }, + { tone: 'ghost' }, + ), + ); + } + return h('div', { class: 'secret-row' }, ...extras); + } + + function fieldFor(variable) { + const key = variable.key; + const isSecretSet = variable.type === 'secret' && view.data.secrets[key] && !(key in view.edits); + const help = [ + variable.help, + isSecretSet ? 'Une valeur est déjà enregistrée : laisse vide pour la conserver.' : null, + variable.restartRequired ? 'Prise en compte au prochain démarrage du bot.' : null, + ] + .filter(Boolean) + .join(' '); + + const wrapper = field(`${variable.label}${variable.required ? ' *' : ''}`, controlFor(variable), { + help, + error: view.errors[key], + }); + wrapper.append( + h('span', { class: 'field-help', text: key, style: { fontFamily: 'var(--mono)', opacity: '0.6' } }), + ); + return variable.advanced ? h('div', { class: 'advanced-wrapper' }, wrapper) : wrapper; + } + + async function showPreview() { + const { content } = await api.post('/api/configuration/preview', { values: view.edits }); + mount( + previewHost, + card( + 'Aperçu du fichier .env', + { subtitle: 'Les secrets sont masqués dans cet aperçu.' }, + h('pre', {}, h('code', { text: content })), + ), + ); + } + + async function save({ force = false } = {}) { + try { + const result = await api.post('/api/configuration/save', { values: view.edits, force }); + view.lastSave = result; + view.edits = {}; + view.data = await api.get('/api/configuration'); + view.errors = view.data.errors; + view.warnings = view.data.warnings; + view.missing = view.data.missingRequired; + view.diff = []; + toast(result.written ? 'Configuration enregistrée.' : 'Aucun changement à enregistrer.', 'success'); + draw(); + } catch (error) { + toast(error.message, 'error'); + if (error.details) { + view.errors = error.details; + draw(); + } + } + } + + const previewHost = h('div', {}); + + function stepList() { + return h( + 'div', + { class: 'wizard-steps' }, + view.data.sections.map((section, index) => { + const status = sectionStatus(view, section.id); + const classes = ['wizard-step']; + if (index === view.step) classes.push('active'); + if (status.invalid || status.missing) classes.push('invalid'); + else if (status.filled) classes.push('done'); + + return h( + 'button', + { + class: classes.join(' '), + type: 'button', + onClick: () => { + view.step = index; + draw(); + }, + }, + h('span', { class: 'dot', text: status.invalid || status.missing ? '!' : String(index + 1) }), + h( + 'span', + {}, + h('strong', { text: section.title }), + h('span', { class: 'muted', text: section.summary }), + ), + ); + }), + ); + } + + function stepBody() { + const section = view.data.sections[view.step]; + const variables = view.data.variables.filter( + (variable) => variable.section === section.id && (view.showAdvanced || !variable.advanced), + ); + const hiddenCount = view.data.variables.filter( + (variable) => variable.section === section.id && variable.advanced, + ).length; + + return card( + section.title, + { + subtitle: section.summary, + actions: [ + button( + view.step === 0 ? '' : '← Précédent', + () => { + view.step = Math.max(0, view.step - 1); + draw(); + }, + { tone: 'ghost', disabled: view.step === 0 }, + ), + button( + 'Suivant →', + () => { + view.step = Math.min(view.data.sections.length - 1, view.step + 1); + draw(); + }, + { tone: 'ghost', disabled: view.step === view.data.sections.length - 1 }, + ), + ], + }, + section.intro && h('p', { text: section.intro }), + + section.steps?.length > 0 && + h( + 'ol', + { class: 'steps-list' }, + section.steps.map((step) => h('li', {}, richText(fillPlaceholders(view, step), 'rich-inline'))), + ), + + section.links?.length > 0 && + h( + 'div', + { class: 'row' }, + section.links.map((link) => + h('a', { + class: 'btn btn-ghost', + href: link.url, + target: '_blank', + rel: 'noreferrer', + text: `↗ ${link.label}`, + }), + ), + ), + + hiddenCount > 0 && + toggle( + view.showAdvanced, + (checked) => { + view.showAdvanced = checked; + draw(); + }, + `Afficher les ${hiddenCount} options avancées`, + ), + + ...variables.map(fieldFor), + ); + } + + function summary() { + const blocking = view.missing.length > 0 || Object.keys(view.errors).length > 0; + + return card( + 'Enregistrement', + { + subtitle: view.data.exists + ? 'Le fichier .env actuel sera sauvegardé avant d’être remplacé.' + : 'Aucun .env pour l’instant : il sera créé avec les permissions 600.', + actions: [ + button('Aperçu', showPreview, { tone: 'ghost' }), + button('Enregistrer le .env', () => save(), { tone: 'primary', disabled: blocking }), + ], + }, + + view.missing.length > 0 && + notice(`Valeurs obligatoires manquantes : ${view.missing.join(', ')}.`, 'error'), + + Object.keys(view.errors).length > 0 && + notice( + `${Object.keys(view.errors).length} champ(s) invalide(s) : ${Object.keys(view.errors).join(', ')}.`, + 'error', + ), + + ...view.warnings.map((warning) => notice(warning, 'warning')), + + view.diff.length > 0 && + h( + 'div', + { class: 'stack' }, + h('h3', { text: `${view.diff.length} changement(s) en attente` }), + h( + 'div', + { class: 'diff stack' }, + view.diff.map((entry) => + h( + 'div', + {}, + h('strong', { text: `${entry.key} ` }), + h('del', { text: entry.before || '(vide)' }), + ' → ', + h('ins', { text: entry.after || '(vide)' }), + entry.restartRequired && h('span', { class: 'muted', text: ' · redémarrage requis' }), + ), + ), + ), + ), + + view.lastSave?.written && + notice( + `Fichier écrit.${view.lastSave.backup ? ` Sauvegarde : ${view.lastSave.backup}.` : ''}${ + view.lastSave.restartRequired ? ' Redémarre le bot pour appliquer les changements.' : '' + }`, + 'success', + ), + + view.data.unknownKeys.length > 0 && + notice( + `Variables inconnues conservées telles quelles : ${view.data.unknownKeys.join(', ')}.`, + 'info', + ), + ); + } + + function draw() { + mount( + container, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Configuration du bot' }), + h('p', { + class: 'muted', + text: 'Chaque valeur est expliquée, vérifiée puis écrite dans le fichier .env. Rien n’est enregistré avant ta validation.', + }), + ), + ), + standalone && + notice( + 'Session d’amorçage : seule cette page est accessible. Une fois le .env enregistré, redémarre le bot et connecte-toi avec Discord.', + 'info', + ), + h( + 'div', + { class: 'wizard' }, + stepList(), + h('div', { class: 'stack' }, stepBody(), summary(), previewHost), + ), + ), + ); + } + + draw(); +} diff --git a/src/web/public/views/tasks.js b/src/web/public/views/tasks.js new file mode 100644 index 0000000..2cd7717 --- /dev/null +++ b/src/web/public/views/tasks.js @@ -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(); +} diff --git a/src/web/public/views/wiki.js b/src/web/public/views/wiki.js new file mode 100644 index 0000000..5979ac8 --- /dev/null +++ b/src/web/public/views/wiki.js @@ -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.' }, + ), + ), + ); + }, + ); +} diff --git a/src/web/public/wiki.css b/src/web/public/wiki.css new file mode 100644 index 0000000..1d47d73 --- /dev/null +++ b/src/web/public/wiki.css @@ -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; + } +} diff --git a/src/web/router.js b/src/web/router.js new file mode 100644 index 0000000..015d77d --- /dev/null +++ b/src/web/router.js @@ -0,0 +1,63 @@ +import { HttpError, notFound } from './http.js'; + +/** + * Minimal router: `/api/repositories/:owner/:repo` style patterns, no dependency (M16-T01). + * A trailing `*` captures the rest of the path under `params.rest`. + */ + +function compile(pattern) { + const segments = pattern.split('/').filter(Boolean); + return { segments, pattern }; +} + +function match(route, segments) { + const params = {}; + for (const [index, expected] of route.segments.entries()) { + if (expected === '*') { + params.rest = segments.slice(index).join('/'); + return params; + } + const actual = segments[index]; + if (actual === undefined) return null; + if (expected.startsWith(':')) params[expected.slice(1)] = decodeURIComponent(actual); + else if (expected !== actual) return null; + } + return segments.length === route.segments.length ? params : null; +} + +export function createRouter() { + const routes = []; + + const add = (method, pattern, handler, options = {}) => { + routes.push({ method, ...compile(pattern), handler, options }); + }; + + return { + get: (pattern, handler, options) => add('GET', pattern, handler, options), + post: (pattern, handler, options) => add('POST', pattern, handler, options), + put: (pattern, handler, options) => add('PUT', pattern, handler, options), + patch: (pattern, handler, options) => add('PATCH', pattern, handler, options), + delete: (pattern, handler, options) => add('DELETE', pattern, handler, options), + + /** + * Finds the handler for a request. + * Throws 405 when the path exists under another method, which is easier to + * debug from the browser console than a plain 404. + */ + resolve(method, pathname) { + const segments = pathname.split('/').filter(Boolean); + let pathMatched = false; + + for (const route of routes) { + const params = match(route, segments); + if (!params) continue; + pathMatched = true; + if (route.method === method) return { ...route, params }; + } + + throw pathMatched ? new HttpError(405, `Méthode ${method} non autorisée ici`) : notFound(); + }, + + list: () => routes.map((route) => `${route.method} ${route.pattern}`), + }; +} diff --git a/src/web/server.js b/src/web/server.js new file mode 100644 index 0000000..2d954c3 --- /dev/null +++ b/src/web/server.js @@ -0,0 +1,269 @@ +import { createServer } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { env } from '../config/env.js'; +import { ExternalApiError, PermissionDeniedError, UserFacingError } from '../core/errors.js'; +import { createLogger } from '../core/logger.js'; +import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js'; +import { registerApiRoutes } from './api/index.js'; +import { authenticate, assertSameOrigin } from './auth/session.js'; +import { authorize } from './auth/guard.js'; +import { broadcast, closeEventStreams, topicForPath } from './events.js'; +import { HttpError, readJsonBody, readRawBody, sendEmpty, sendHtml, sendJson, sendStatic } from './http.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). */ + +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'); + +/** Sliding window per client address, reset every minute. */ +function createRateLimiter(limit) { + const hits = new Map(); + let windowStart = Date.now(); + + return (key) => { + const now = Date.now(); + if (now - windowStart >= 60_000) { + hits.clear(); + windowStart = now; + } + const count = (hits.get(key) ?? 0) + 1; + hits.set(key, count); + return count <= limit; + }; +} + +function statusOf(error) { + if (error instanceof HttpError) return error.status; + if (error instanceof PermissionDeniedError) return 403; + if (error instanceof UserFacingError) return 400; + if (error instanceof ExternalApiError) return 502; + return 500; +} + +/** + * Builds the request handler. Exported on its own so the tests can drive it + * without opening a socket. + */ +export function createHandler({ client = null, setupOnly = false, startedAt = Date.now() } = {}) { + const router = registerApiRoutes(createRouter(), { setupOnly }); + const context = { client, setupOnly, startedAt }; + const allowWithinRate = createRateLimiter(env.web.rateLimitPerMinute); + + // The webhook shares the port when both servers are configured on it. + const sharesWebhookPort = env.webhook.enabled && env.webhook.port === env.web.port; + + return async function handle(request, response) { + const url = new URL(request.url, `http://${request.headers.host ?? 'localhost'}`); + const pathname = url.pathname; + + if (sharesWebhookPort && request.method === 'POST' && pathname === env.webhook.path) { + try { + const rawBody = await readRawBody(request); + response.writeHead(await handleGiteaWebhook(client, request.headers, rawBody)).end(); + } catch (error) { + log.error('Webhook handling failed', error); + response.writeHead(500).end(); + } + return; + } + + const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/'); + if (!isApi) { + // The wiki is rendered here rather than in the browser: a terms page + // that needs scripts to show its text reads as blank to anything that + // 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, 'État indisponible

    État indisponible.'); + } + return; + } + + const served = await sendStatic(response, publicDir, pathname, { + fallback: 'index.html', + request, + }); + if (!served) sendEmpty(response, 404); + return; + } + + if (!allowWithinRate(request.socket.remoteAddress ?? 'unknown')) { + sendJson(response, 429, { error: 'Trop de requêtes, réessaie dans une minute.' }); + return; + } + + try { + const route = router.resolve(request.method, pathname); + const actor = authenticate(request); + assertSameOrigin(request, actor); + authorize(actor, route.options); + + const body = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method) + ? await readJsonBody(request) + : {}; + + const result = await route.handler({ + request, + response, + params: route.params, + query: url.searchParams, + body, + actor, + context, + }); + + // A handler that wrote the response itself (a redirect, an event stream) + // returns nothing. + if (!response.headersSent) sendJson(response, 200, result ?? { ok: true }); + + // Announce the change only once it has gone through, so a dashboard never + // refreshes on a write that was rejected. + if (request.method !== 'GET') { + broadcast(topicForPath(pathname), { path: pathname, method: request.method }); + } + } catch (error) { + const status = statusOf(error); + if (status >= 500) log.error(`${request.method} ${pathname} failed`, error); + else log.debug(`${request.method} ${pathname} rejected with ${status}`, { message: error.message }); + + if (!response.headersSent) { + sendJson(response, status, { + error: status >= 500 ? 'Une erreur interne est survenue.' : error.message, + ...(error.details && { details: error.details }), + }); + } + } + }; +} + +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() })); + + server.listen(env.web.port, env.web.host, () => { + 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 }); + + // 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, + ); + }); + // Open event streams would otherwise keep the server from closing. + server.on('close', closeEventStreams); + return server; +} + +/** True when the webhook server does not need its own port. */ +export function webhookSharesWebPort() { + return env.web.enabled && env.webhook.enabled && env.webhook.port === env.web.port; +} diff --git a/src/web/services/build-info.js b/src/web/services/build-info.js new file mode 100644 index 0000000..1b4d7f3 --- /dev/null +++ b/src/web/services/build-info.js @@ -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; +} diff --git a/src/web/services/deploy-service.js b/src/web/services/deploy-service.js new file mode 100644 index 0000000..b780fca --- /dev/null +++ b/src/web/services/deploy-service.js @@ -0,0 +1,235 @@ +import { spawn } from 'node:child_process'; +import { createHmac } from 'node:crypto'; +import { COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { + createDeployment, + finishDeployment, + listAutoTargets, + markRunning, +} from '../../database/repositories/deploy-repository.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { notify } from '../../services/notifications/notification-service.js'; +import { splitRepository, repos } from '../../services/gitea/gitea-admin.js'; +import { broadcast } from '../events.js'; +import { HttpError, badRequest, forbidden } from '../http.js'; + +/** Runs a deployment for a target and records its outcome (M16-T07). */ + +const log = createLogger('web:deploy'); +const MAX_LOG_CHARS = 60_000; + +/** Keeps the tail of a long output: the failure is almost always at the end. */ +const trimLog = (text) => + text.length <= MAX_LOG_CHARS + ? text + : `… (${text.length - MAX_LOG_CHARS} caractères tronqués)\n${text.slice(-MAX_LOG_CHARS)}`; + +export function describeTarget(target) { + switch (target.kind) { + case 'webhook': + return `POST ${target.config.url}`; + case 'command': + return target.config.command; + case 'gitea-action': + return `workflow ${target.config.workflow} sur ${target.config.ref ?? 'main'}`; + default: + return target.kind; + } +} + +/** Rejects a target whose configuration cannot possibly run. */ +export function assertRunnable(target) { + if (!target.enabled) throw badRequest('Cette cible est désactivée.'); + + if (target.kind === 'webhook') { + if (!target.config.url) throw badRequest('Cette cible webhook n’a pas d’URL.'); + return; + } + if (target.kind === 'command') { + if (!env.web.allowCommandDeploys) { + throw forbidden('Les déploiements par commande sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS`).'); + } + if (!target.config.command) throw badRequest('Cette cible n’a pas de commande.'); + return; + } + if (target.kind === 'gitea-action') { + if (!target.config.workflow) throw badRequest('Cette cible n’a pas de workflow.'); + return; + } + throw badRequest(`Type de cible inconnu : ${target.kind}`); +} + +async function runWebhook(target, payload) { + const body = JSON.stringify(payload); + const headers = { 'Content-Type': 'application/json', 'User-Agent': 'FWS-Bot' }; + if (target.config.secret) { + headers['X-FWS-Signature'] = createHmac('sha256', target.config.secret).update(body).digest('hex'); + } + Object.assign(headers, target.config.headers ?? {}); + + const response = await fetch(target.config.url, { + method: target.config.method ?? 'POST', + headers, + body, + signal: AbortSignal.timeout(Math.min(env.web.deployTimeoutMs, 120_000)), + }); + const text = await response.text().catch(() => ''); + + if (!response.ok) { + throw new HttpError(502, `Le webhook a répondu ${response.status}`, trimLog(text)); + } + return `HTTP ${response.status}\n${trimLog(text)}`; +} + +/** + * Runs the configured shell command. Gated by `WEB_ALLOW_COMMAND_DEPLOYS` and by + * the Owner access level: it executes arbitrary code on the bot host. + */ +function runCommand(target, payload) { + return new Promise((resolve, reject) => { + const child = spawn(target.config.command, { + shell: true, + cwd: target.config.cwd || process.cwd(), + env: { + ...process.env, + FWS_DEPLOY_REPOSITORY: payload.repository, + FWS_DEPLOY_ENVIRONMENT: payload.environment, + FWS_DEPLOY_REF: payload.ref ?? '', + FWS_DEPLOY_TAG: payload.releaseTag ?? '', + }, + timeout: env.web.deployTimeoutMs, + }); + + let output = ''; + const collect = (chunk) => { + output += chunk; + if (output.length > MAX_LOG_CHARS * 2) output = output.slice(-MAX_LOG_CHARS); + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + + child.on('error', reject); + child.on('close', (code, signal) => { + const rendered = trimLog(output); + if (code === 0) resolve(rendered); + else reject(new HttpError(500, `La commande s’est terminée avec le code ${code ?? signal}`, rendered)); + }); + }); +} + +async function runGiteaAction(target, payload) { + const parts = splitRepository(target.repository); + if (!parts) throw badRequest(`Dépôt invalide : ${target.repository}`); + + await repos.dispatchWorkflow(parts.owner, parts.repo, target.config.workflow, { + ref: target.config.ref || payload.ref || 'main', + inputs: { ...(target.config.inputs ?? {}), environment: payload.environment }, + }); + return `Workflow ${target.config.workflow} déclenché sur ${target.config.ref || payload.ref || 'main'}.`; +} + +/** + * Executes a deployment end to end: history row, run, outcome, Discord notice. + * Never throws — the caller reads the returned record to know what happened. + */ +export async function runDeployment( + client, + target, + { ref = null, releaseTag = null, source = 'web', triggeredBy = null, guildId } = {}, +) { + assertRunnable(target); + + // The history belongs to the guild that owns the target, not to whichever guild + // the process happens to be configured with. + guildId ??= target.guild_id ?? env.discord.guildId; + + const deployment = createDeployment({ + guildId, + targetId: target.id, + targetName: target.name, + repository: target.repository, + environment: target.environment, + ref, + releaseTag, + source, + triggeredBy, + }); + markRunning(deployment.id); + broadcast('deployments', { id: deployment.id, status: 'running', target: target.name }); + + const payload = { + deploymentId: deployment.id, + repository: target.repository, + environment: target.environment, + target: target.name, + ref, + releaseTag, + triggeredBy, + source, + }; + + log.info('Deployment started', { id: deployment.id, target: target.name, kind: target.kind }); + + try { + let output; + if (target.kind === 'webhook') output = await runWebhook(target, payload); + else if (target.kind === 'command') output = await runCommand(target, payload); + else output = await runGiteaAction(target, payload); + + finishDeployment(deployment.id, { status: 'success', log: output }); + broadcast('deployments', { id: deployment.id, status: 'success', target: target.name }); + logEvent({ guildId, type: 'deploy.success', actorId: triggeredBy, payload }); + await announce(client, { ...payload, status: 'success' }); + return { ...deployment, status: 'success', log: output }; + } catch (error) { + const details = error.details ?? error.message; + finishDeployment(deployment.id, { status: 'failed', log: details, error: error.message }); + broadcast('deployments', { id: deployment.id, status: 'failed', target: target.name }); + log.error('Deployment failed', error); + logEvent({ guildId, type: 'deploy.failed', actorId: triggeredBy, payload }); + await announce(client, { ...payload, status: 'failed', error: error.message }); + return { ...deployment, status: 'failed', log: details, error: error.message }; + } +} + +/** Publishes the outcome in the releases channel, errors in the errors channel. */ +async function announce(client, result) { + if (!client) return; + + const success = result.status === 'success'; + const embed = { + title: success + ? `Déploiement réussi — ${result.environment}` + : `Déploiement en échec — ${result.environment}`, + color: success ? COLORS.success : COLORS.error, + fields: [ + { name: 'Dépôt', value: result.repository, inline: true }, + { name: 'Cible', value: result.target, inline: true }, + { name: 'Version', value: result.releaseTag || result.ref || '—', inline: true }, + ], + ...(result.error && { description: `\`\`\`${String(result.error).slice(0, 500)}\`\`\`` }), + timestamp: new Date().toISOString(), + }; + + await notify(client, success ? 'releases' : 'errors', { embeds: [embed] }).catch((error) => + log.warn('Could not publish the deployment notification', error), + ); +} + +/** Fires every auto-deploy target of a repository, one after the other (M16-T08). */ +export async function runAutoDeployments(client, { repository, releaseTag, ref, triggeredBy = null }) { + const guildId = env.discord.guildId; + const targets = listAutoTargets({ guildId, repository }); + const results = []; + + for (const target of targets) { + try { + results.push(await runDeployment(client, target, { ref, releaseTag, source: 'auto', triggeredBy })); + } catch (error) { + log.warn('Auto deployment skipped', { target: target.name, reason: error.message }); + } + } + return results; +} diff --git a/src/web/services/env-file.js b/src/web/services/env-file.js new file mode 100644 index 0000000..a8228a5 --- /dev/null +++ b/src/web/services/env-file.js @@ -0,0 +1,160 @@ +import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { createLogger } from '../../core/logger.js'; +import { BY_KEY, SECTIONS, VARIABLES, isSecret } from './env-schema.js'; + +/** Reading and writing `.env` from the configuration wizard (M16-T09). */ + +const log = createLogger('web:env'); + +export const envFilePath = () => path.resolve(process.cwd(), '.env'); + +/** Parses a `.env` body. Unknown keys are kept so the wizard never loses them. */ +export function parseEnv(content) { + const values = {}; + for (const rawLine of content.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line === '' || line.startsWith('#')) continue; + + const separator = line.indexOf('='); + if (separator < 0) continue; + + const key = line + .slice(0, separator) + .trim() + .replace(/^export\s+/, ''); + let value = line.slice(separator + 1).trim(); + if ( + (value.startsWith('"') && value.endsWith('"') && value.length > 1) || + (value.startsWith("'") && value.endsWith("'") && value.length > 1) + ) { + value = value.slice(1, -1); + } + values[key] = value; + } + return values; +} + +export function readEnvFile(file = envFilePath()) { + if (!existsSync(file)) return { exists: false, values: {}, unknown: {} }; + + const values = parseEnv(readFileSync(file, 'utf8')); + const unknown = Object.fromEntries(Object.entries(values).filter(([key]) => !(key in BY_KEY))); + return { exists: true, values, unknown }; +} + +/** Quotes only when needed, so the file stays readable. */ +function renderValue(value) { + const text = String(value ?? ''); + return /[\s#"'$]/.test(text) ? JSON.stringify(text) : text; +} + +/** + * Rebuilds `.env` from the schema so every variable ships with its explanation. + * Unknown keys are appended at the end rather than dropped. + */ +export function renderEnvFile(values, unknown = {}) { + const lines = [ + '# =============================================================================', + '# FWS-Bot — configuration', + `# Généré par l'assistant du tableau de bord le ${new Date().toISOString()}`, + '# Ne jamais committer ce fichier : il contient des secrets.', + '# =============================================================================', + ]; + + for (const section of SECTIONS) { + const variables = VARIABLES.filter((item) => item.section === section.id); + if (variables.length === 0) continue; + + lines.push('', `# --- ${section.title} ${'-'.repeat(Math.max(3, 72 - section.title.length))}`); + if (section.summary) lines.push(`# ${section.summary}`); + + for (const variable of variables) { + lines.push(`# ${variable.label} — ${variable.help}`); + const value = values[variable.key] ?? variable.default ?? ''; + lines.push(`${variable.key}=${renderValue(value)}`); + } + } + + const extras = Object.entries(unknown); + if (extras.length > 0) { + lines.push('', '# --- Variables conservées telles quelles ---------------------------------'); + for (const [key, value] of extras) lines.push(`${key}=${renderValue(value)}`); + } + + return `${lines.join('\n')}\n`; +} + +/** + * Writes `.env` after backing up the previous version. + * The file is chmod 600: it holds the bot token. + */ +export function writeEnvFile(values, { unknown = {}, file = envFilePath() } = {}) { + let backup = null; + if (existsSync(file)) { + backup = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`; + copyFileSync(file, backup); + } else { + mkdirSync(path.dirname(file), { recursive: true }); + } + + writeFileSync(file, renderEnvFile(values, unknown), { encoding: 'utf8', mode: 0o600 }); + // `writeFileSync` only applies `mode` when it creates the file. + chmodSync(file, 0o600); + + log.info('Configuration file written', { file, backup }); + return { file, backup }; +} + +/** Never sends a secret back to the browser: only whether it is filled in. */ +export function maskValues(values) { + const masked = {}; + for (const variable of VARIABLES) { + const value = values[variable.key] ?? ''; + masked[variable.key] = isSecret(variable.key) ? '' : value; + } + return masked; +} + +export function secretStatus(values) { + return Object.fromEntries( + VARIABLES.filter((item) => item.type === 'secret').map((item) => [ + item.key, + Boolean(String(values[item.key] ?? '').trim()), + ]), + ); +} + +/** + * Merges a submitted patch into the stored values. + * An empty secret means « keep the current one », otherwise clearing a field by + * accident would silently destroy the token. + */ +export function mergeValues(current, patch) { + const merged = { ...current }; + for (const [key, value] of Object.entries(patch)) { + if (!(key in BY_KEY)) continue; + const text = String(value ?? '').trim(); + if (isSecret(key) && text === '') continue; + merged[key] = text; + } + return merged; +} + +/** Human readable summary of what a save would change, secrets never revealed. */ +export function diffValues(current, next) { + return VARIABLES.map((variable) => { + const before = String(current[variable.key] ?? ''); + const after = String(next[variable.key] ?? ''); + if (before === after) return null; + return { + key: variable.key, + section: variable.section, + label: variable.label, + secret: isSecret(variable.key), + restartRequired: Boolean(variable.restartRequired), + before: isSecret(variable.key) ? (before ? '••••••' : '') : before, + after: isSecret(variable.key) ? (after ? '••••••' : '') : after, + }; + }).filter(Boolean); +} diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js new file mode 100644 index 0000000..bfb2b44 --- /dev/null +++ b/src/web/services/env-schema.js @@ -0,0 +1,764 @@ +/** + * Documented description of every `.env` variable (M16-T09). + * + * This file is the single source of truth of the configuration wizard: the form, + * the explanations, the validation and the generated `.env` all derive from it. + * Adding a variable to the bot means adding it here, nowhere else. + */ + +const SNOWFLAKE = /^\d{17,20}$/; + +/** Wizard steps, in the order the user walks through them. */ +export const SECTIONS = Object.freeze([ + { + id: 'discord', + title: 'Application Discord', + summary: 'Identité du bot. Sans ces trois valeurs, le bot ne démarre pas.', + intro: + 'Une « application » Discord héberge ton bot. Elle se crée en deux minutes et fournit un token (le mot de passe du bot) et un identifiant public.', + steps: [ + 'Ouvre le Discord Developer Portal puis clique sur **New Application**.', + 'Onglet **Bot** → **Reset Token** → copie la valeur : c’est `DISCORD_TOKEN`.', + 'Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent**.', + 'Onglet **General Information** → copie l’**Application ID** : c’est `DISCORD_CLIENT_ID`.', + 'Sur Discord, active **Paramètres → Avancés → Mode développeur**, puis clic droit sur ton serveur → **Copier l’identifiant** : c’est `DISCORD_GUILD_ID`.', + ], + links: [{ label: 'Discord Developer Portal', url: 'https://discord.com/developers/applications' }], + }, + { + id: 'roles', + title: 'Rôles FWS', + summary: 'Qui a le droit de faire quoi, sur Discord comme sur ce tableau de bord.', + intro: + 'Les quatre niveaux d’accès (Owner, Dev, Staff, Membre) sont déduits des rôles Discord. Crée d’abord les rôles dans **Paramètres du serveur → Rôles**, puis colle leur identifiant ici.', + steps: [ + 'Crée les rôles manquants dans **Paramètres du serveur → Rôles**.', + 'Clic droit sur chaque rôle → **Copier l’identifiant**.', + 'Le propriétaire du serveur est toujours Owner, même sans rôle configuré.', + 'Si rien n’est renseigné, tout le monde est considéré comme simple membre.', + ], + }, + { + id: 'channels', + title: 'Salons Discord', + summary: 'Où le bot publie ses messages : accueil, logs, notifications Gitea.', + intro: + 'Chaque identifiant est facultatif : un salon non renseigné désactive simplement la fonctionnalité associée. Clic droit sur un salon → **Copier l’identifiant**.', + steps: [ + 'Crée les salons souhaités (accueil, logs, notifications…).', + 'Clic droit sur chaque salon → **Copier l’identifiant**.', + 'Pour les catégories, clic droit sur la catégorie elle-même.', + 'Ces valeurs peuvent aussi être changées plus tard depuis l’onglet Paramètres, sans redémarrage.', + ], + }, + { + id: 'voice', + title: 'Salons vocaux temporaires', + summary: 'Le salon « rejoindre pour créer » et sa catégorie d’accueil.', + intro: + 'Quand un membre rejoint le salon déclencheur, le bot lui crée un salon vocal personnel, supprimé automatiquement une fois vide.', + steps: [ + 'Crée un salon vocal nommé par exemple « ➕ Créer un salon ».', + 'Copie son identifiant dans `CHANNEL_VOICE_TRIGGER_ID`.', + '(Facultatif) Crée une catégorie qui accueillera les salons générés.', + ], + }, + { + id: 'gitea', + title: 'Gitea', + summary: 'Accès à l’organisation, aux dépôts, aux issues et aux releases.', + intro: + 'Le tableau de bord lit et écrit dans Gitea avec un jeton d’accès personnel. Donne-lui le minimum de droits nécessaires.', + steps: [ + 'Connecte-toi à ton instance Gitea avec le compte technique de l’organisation.', + 'Va dans **Paramètres → Applications → Générer un nouveau jeton**.', + 'Coche au minimum `read:organization`, `read:repository`, `write:issue` — ajoute `write:repository` pour créer des releases depuis le site.', + 'Copie le jeton immédiatement : Gitea ne le réaffiche jamais.', + ], + }, + { + id: 'webhook', + title: 'Webhooks Gitea', + summary: 'Notifications temps réel des issues, PR, commits et releases.', + intro: + 'Gitea appelle le bot à chaque événement. La requête est signée en HMAC-SHA256 : sans le secret partagé, elle est rejetée.', + steps: [ + 'Active `WEBHOOK_ENABLED` et choisis un port libre.', + 'Génère un secret aléatoire avec le bouton ci-dessous.', + 'Dans Gitea : **Dépôt (ou organisation) → Paramètres → Webhooks → Ajouter → Gitea**.', + 'URL cible : `https://ton-domaine{WEBHOOK_PATH}`, type de contenu `application/json`, secret identique.', + 'Coche les événements Issues, Pull Requests, Push et Releases.', + ], + }, + { + id: 'web', + title: 'Tableau de bord web', + summary: 'Ce site : accès, connexion Discord et pipeline de déploiement.', + intro: + 'Le tableau de bord réutilise la connexion Discord des membres. Il faut donc déclarer une URL de redirection OAuth2 dans le Developer Portal.', + steps: [ + 'Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.', + '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.', + 'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.', + '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' }], + }, + { + id: 'runtime', + title: 'Exécution et journaux', + summary: 'Environnement, verbosité des logs et rétention.', + intro: 'Valeurs sûres par défaut : tu peux passer cette étape et y revenir plus tard.', + steps: [], + }, + { + id: 'database', + title: 'Base de données', + summary: 'Emplacement du fichier SQLite et des sauvegardes.', + intro: + 'La base est un simple fichier. Sauvegarde-la en copiant le dossier `data/` — aucun serveur à installer.', + steps: [], + }, + { + id: 'links', + title: 'Liens publics FWS', + summary: 'Affichés dans les commandes d’aide et sur ce tableau de bord.', + intro: 'Purement cosmétique : ces liens apparaissent dans `/help`, `/fws` et le pied de page du site.', + steps: [], + }, +]); + +/** + * `advanced: true` hides the field behind the « mode avancé » switch. + * `restartRequired: true` warns that the value is only read at startup. + */ +export const VARIABLES = Object.freeze([ + // --- Discord application --------------------------------------------------- + { + key: 'DISCORD_TOKEN', + section: 'discord', + label: 'Token du bot', + help: 'Le mot de passe du bot. Quiconque le possède contrôle le bot : ne le partage jamais et ne le committe jamais.', + type: 'secret', + required: true, + placeholder: 'MTIz...', + restartRequired: true, + testable: 'discord', + }, + { + key: 'DISCORD_CLIENT_ID', + section: 'discord', + label: 'Application ID', + help: 'Identifiant public de l’application. Sert à enregistrer les commandes slash et à construire le lien d’invitation.', + type: 'snowflake', + required: true, + placeholder: '123456789012345678', + restartRequired: true, + }, + { + key: 'DISCORD_GUILD_ID', + section: 'discord', + label: 'Serveur Discord', + help: 'Serveur sur lequel les commandes slash sont enregistrées. L’enregistrement par serveur est instantané, contrairement au global.', + type: 'snowflake', + required: true, + placeholder: '123456789012345678', + restartRequired: true, + }, + + // --- Roles ----------------------------------------------------------------- + { + key: 'ROLE_OWNER_ID', + section: 'roles', + label: 'Rôle Owner', + help: 'Accès complet : configuration, déploiements, suppression de dépôts.', + type: 'snowflake', + }, + { + key: 'ROLE_DEV_ID', + section: 'roles', + label: 'Rôle Dev', + help: 'Gestion des dépôts, des issues, des PR et des releases.', + type: 'snowflake', + }, + { + key: 'ROLE_STAFF_ID', + section: 'roles', + label: 'Rôle Staff', + help: 'Modération, tickets et consultation du tableau de bord.', + type: 'snowflake', + }, + { + key: 'ROLE_MEMBER_ID', + section: 'roles', + label: 'Rôle attribué à l’arrivée', + help: 'Donné automatiquement à chaque nouveau membre du serveur.', + type: 'snowflake', + }, + + // --- Channels -------------------------------------------------------------- + { + key: 'CHANNEL_WELCOME_ID', + section: 'channels', + label: 'Salon d’accueil', + help: 'Message de bienvenue des nouveaux membres.', + type: 'snowflake', + }, + { + key: 'CHANNEL_RULES_ID', + section: 'channels', + label: 'Salon des règles', + help: 'Référencé dans le message de bienvenue.', + type: 'snowflake', + }, + { + key: 'CHANNEL_ANNOUNCEMENTS_ID', + section: 'channels', + label: 'Salon des annonces', + help: 'Cible par défaut des annonces publiées depuis le tableau de bord.', + type: 'snowflake', + }, + { + key: 'CHANNEL_LOGS_ID', + section: 'channels', + label: 'Salon des logs techniques', + help: 'Erreurs et événements techniques du bot.', + type: 'snowflake', + }, + { + key: 'CHANNEL_MOD_LOGS_ID', + section: 'channels', + label: 'Salon des logs de modération', + help: 'Avertissements, exclusions, bannissements.', + type: 'snowflake', + }, + { + key: 'CHANNEL_TICKETS_LOGS_ID', + section: 'channels', + label: 'Salon des logs de tickets', + help: 'Ouverture, prise en charge et clôture des tickets.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_ISSUES_ID', + section: 'channels', + label: 'Notifications — issues', + help: 'Issues Gitea ouvertes, fermées et commentées.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_PULL_REQUESTS_ID', + section: 'channels', + label: 'Notifications — pull requests', + help: 'Ouvertures, mises à jour et merges de PR.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_COMMITS_ID', + section: 'channels', + label: 'Notifications — commits', + help: 'Push sur les branches suivies.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_RELEASES_ID', + section: 'channels', + label: 'Notifications — releases', + help: 'Publication d’une version et résultat des déploiements associés.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_ERRORS_ID', + section: 'channels', + label: 'Notifications — erreurs', + help: 'Échecs d’appels API et de déploiement.', + type: 'snowflake', + }, + { + key: 'CATEGORY_TICKETS_ID', + section: 'channels', + label: 'Catégorie des tickets', + help: 'Catégorie sous laquelle les salons privés de tickets sont créés.', + type: 'snowflake', + }, + + // --- Voice ----------------------------------------------------------------- + { + key: 'CHANNEL_VOICE_TRIGGER_ID', + section: 'voice', + label: 'Salon déclencheur', + help: 'Y entrer crée un salon vocal temporaire dont le membre devient propriétaire.', + type: 'snowflake', + }, + { + key: 'CATEGORY_VOICE_ID', + section: 'voice', + label: 'Catégorie d’accueil', + help: 'Où les salons générés sont créés. Vide : dans la même catégorie que le déclencheur.', + type: 'snowflake', + }, + { + key: 'VOICE_EMPTY_GRACE_MS', + section: 'voice', + label: 'Délai avant suppression (ms)', + help: 'Temps d’attente avant de supprimer un salon devenu vide. `0` supprime immédiatement.', + type: 'int', + default: '5000', + min: 0, + advanced: true, + }, + { + key: 'BOT_STATUS_INTERVAL_SECONDS', + section: 'voice', + label: 'Rotation des statuts (s)', + help: 'Rythme de rotation de la présence du bot. Modifiable à chaud par `/status interval`.', + type: 'int', + default: '60', + min: 5, + advanced: true, + }, + + // --- Gitea ----------------------------------------------------------------- + { + key: 'GITEA_URL', + section: 'gitea', + label: 'URL de l’instance', + help: 'Racine de l’instance Gitea, sans `/api/v1` ni barre oblique finale.', + type: 'url', + placeholder: 'https://gitea.exemple.org', + }, + { + key: 'GITEA_TOKEN', + section: 'gitea', + label: 'Jeton d’accès', + help: 'Jeton personnel de l’organisation. Portée minimale : lecture des dépôts et écriture des issues.', + type: 'secret', + testable: 'gitea', + }, + { + key: 'GITEA_OWNER', + section: 'gitea', + label: 'Organisation', + help: 'Nom de l’organisation propriétaire des dépôts, tel qu’il apparaît dans les URL.', + type: 'text', + placeholder: 'FWS', + }, + { + key: 'GITEA_REPO', + section: 'gitea', + label: 'Dépôt principal', + help: 'Dépôt visé par défaut par les commandes Discord `/issue` et `/pr`.', + type: 'text', + placeholder: 'FWS-Arch', + }, + { + key: 'GITEA_TIMEOUT_MS', + section: 'gitea', + label: 'Délai d’expiration (ms)', + help: 'Au-delà, l’appel est abandonné puis réessayé.', + type: 'int', + default: '10000', + min: 1000, + advanced: true, + }, + { + key: 'GITEA_MAX_RETRIES', + section: 'gitea', + label: 'Tentatives supplémentaires', + help: 'Uniquement sur les erreurs transitoires (délai dépassé, 429, 5xx).', + type: 'int', + default: '2', + min: 0, + advanced: true, + }, + + // --- Webhooks -------------------------------------------------------------- + { + key: 'WEBHOOK_ENABLED', + section: 'webhook', + label: 'Activer la réception des webhooks', + help: 'Démarre le serveur HTTP qui reçoit les événements Gitea.', + type: 'bool', + default: 'false', + restartRequired: true, + }, + { + key: 'WEBHOOK_HOST', + section: 'webhook', + label: 'Interface d’écoute', + help: '`0.0.0.0` écoute sur toutes les interfaces, `127.0.0.1` seulement en local.', + type: 'text', + default: '0.0.0.0', + advanced: true, + restartRequired: true, + }, + { + key: 'WEBHOOK_PORT', + section: 'webhook', + label: 'Port', + help: 'Port du serveur de webhooks. Peut être identique à celui du tableau de bord : les deux partagent alors le même serveur.', + type: 'int', + default: '3000', + min: 1, + max: 65535, + restartRequired: true, + }, + { + key: 'WEBHOOK_PATH', + section: 'webhook', + label: 'Chemin d’écoute', + help: 'Chemin exact à configurer côté Gitea.', + type: 'text', + default: '/webhooks/gitea', + pattern: '^/[\\w\\-/]*$', + advanced: true, + restartRequired: true, + }, + { + key: 'GITEA_WEBHOOK_SECRET', + section: 'webhook', + label: 'Secret partagé', + help: 'Doit être strictement identique à celui saisi dans Gitea. Une signature invalide fait rejeter l’événement.', + type: 'secret', + generator: 'hex32', + }, + + // --- Web dashboard --------------------------------------------------------- + { + key: 'WEB_ENABLED', + section: 'web', + label: 'Activer le tableau de bord', + help: 'Sert ce site depuis le processus du bot.', + type: 'bool', + default: 'false', + restartRequired: true, + }, + { + key: 'WEB_HOST', + section: 'web', + label: 'Interface d’écoute', + 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', + default: '127.0.0.1', + restartRequired: true, + }, + { + key: 'WEB_PORT', + section: 'web', + label: 'Port', + help: 'Port d’écoute du tableau de bord.', + type: 'int', + default: '3080', + min: 1, + max: 65535, + restartRequired: true, + }, + { + key: 'WEB_PUBLIC_URL', + section: 'web', + label: 'URL publique', + help: 'URL de partage du site, utilisée dans les liens. La redirection OAuth2 est déduite de l’adresse réellement utilisée par le navigateur : ce champ n’est qu’un repli.', + type: 'url', + placeholder: 'https://bot.exemple.org', + restartRequired: true, + }, + { + key: 'DISCORD_CLIENT_SECRET', + section: 'web', + label: 'Client Secret OAuth2', + help: 'Developer Portal → OAuth2 → Client Secret. Nécessaire pour connecter les membres au tableau de bord.', + type: 'secret', + restartRequired: true, + }, + { + key: 'WEB_SESSION_SECRET', + section: 'web', + label: 'Clé de signature des sessions', + help: 'Protège les cookies de session. La changer déconnecte tout le monde.', + type: 'secret', + generator: 'hex32', + restartRequired: true, + }, + { + key: 'WEB_SESSION_TTL_HOURS', + section: 'web', + label: 'Durée d’une session (h)', + help: 'Au-delà, l’utilisateur doit se reconnecter.', + type: 'int', + default: '12', + min: 1, + advanced: true, + }, + { + key: 'WEB_SETUP_TOKEN', + section: 'web', + label: 'Jeton d’amorçage', + help: 'Ouvre cet assistant sans compte Discord. À vider une fois la configuration terminée.', + type: 'secret', + generator: 'hex16', + 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', + section: 'web', + label: 'Autoriser les déploiements par commande', + help: 'Permet d’exécuter une commande shell sur le serveur depuis le site. Réservé au niveau Owner : n’active cela que si tu comprends la portée du risque.', + type: 'bool', + default: 'false', + advanced: true, + restartRequired: true, + }, + { + key: 'WEB_ALLOW_RESTART', + section: 'web', + label: 'Autoriser le redémarrage du bot', + help: 'Affiche un bouton de redémarrage. N’a de sens que derrière un superviseur (systemd, pm2, Docker) qui relance le processus.', + type: 'bool', + default: 'false', + advanced: true, + restartRequired: true, + }, + { + key: 'WEB_DEPLOY_TIMEOUT_MS', + section: 'web', + label: 'Délai maximal d’un déploiement (ms)', + help: 'Au-delà, le déploiement est marqué en échec et la commande interrompue.', + type: 'int', + default: '900000', + min: 1000, + advanced: true, + }, + { + key: 'WEB_RATE_LIMIT_PER_MINUTE', + section: 'web', + label: 'Requêtes API par minute', + help: 'Limite par adresse IP, toutes routes confondues.', + type: 'int', + default: '240', + min: 10, + advanced: true, + restartRequired: true, + }, + + // --- Runtime --------------------------------------------------------------- + { + key: 'NODE_ENV', + section: 'runtime', + label: 'Environnement', + help: '`production` en service réel, `development` en local.', + type: 'enum', + options: ['development', 'production', 'test'], + default: 'development', + restartRequired: true, + }, + { + key: 'LOG_LEVEL', + section: 'runtime', + label: 'Niveau de journalisation', + help: '`debug` est bavard et utile pour diagnostiquer, `info` convient au quotidien.', + type: 'enum', + options: ['debug', 'info', 'warn', 'error'], + default: 'info', + restartRequired: true, + }, + { + key: 'LOG_DIR', + section: 'runtime', + label: 'Dossier des journaux', + help: 'Un fichier JSON par jour y est écrit.', + type: 'path', + default: './logs', + advanced: true, + restartRequired: true, + }, + { + key: 'LOG_RETENTION_DAYS', + section: 'runtime', + label: 'Rétention (jours)', + help: 'Durée de conservation des événements fonctionnels en base.', + type: 'int', + default: '30', + min: 1, + advanced: true, + }, + + // --- Database -------------------------------------------------------------- + { + key: 'DATABASE_PATH', + section: 'database', + label: 'Fichier SQLite', + help: 'Chemin du fichier de base. Le dossier est créé s’il n’existe pas.', + type: 'path', + default: './data/fws-bot.sqlite', + restartRequired: true, + }, + { + key: 'BACKUP_DIR', + section: 'database', + label: 'Dossier des sauvegardes', + help: 'Destination des copies de la base déclenchées depuis le tableau de bord.', + type: 'path', + default: './data/backups', + advanced: true, + }, + + // --- Links ----------------------------------------------------------------- + { + key: 'FWS_WEBSITE_URL', + section: 'links', + label: 'Site web', + help: 'Affiché dans `/fws` et dans le pied de page du tableau de bord.', + type: 'url', + }, + { + key: 'FWS_DOCS_URL', + section: 'links', + label: 'Documentation', + help: 'Lien vers la documentation publique du projet.', + type: 'url', + }, + { + key: 'FWS_DISCORD_INVITE_URL', + section: 'links', + label: 'Invitation Discord', + help: 'Lien d’invitation permanent du serveur.', + type: 'url', + }, + { + key: 'FWS_ARCH_REPO_URL', + section: 'links', + label: 'Dépôt FWS Arch', + help: 'Lien direct vers le dépôt principal.', + type: 'url', + }, +]); + +export const BY_KEY = Object.freeze(Object.fromEntries(VARIABLES.map((item) => [item.key, item]))); + +export const isSecret = (key) => BY_KEY[key]?.type === 'secret'; + +/** Variables the bot refuses to start without. */ +export const requiredKeys = () => VARIABLES.filter((item) => item.required).map((item) => item.key); + +/** + * Validates one value against its declaration. + * Returns null when valid, a French message otherwise. + */ +export function validateValue(key, rawValue) { + const variable = BY_KEY[key]; + if (!variable) return `Variable inconnue : ${key}`; + + const value = String(rawValue ?? '').trim(); + if (value === '') return variable.required ? 'Cette valeur est obligatoire.' : null; + if (value.includes('\n')) return 'Les retours à la ligne ne sont pas autorisés.'; + + switch (variable.type) { + case 'snowflake': + return SNOWFLAKE.test(value) + ? null + : 'Un identifiant Discord est composé de 17 à 20 chiffres (active le mode développeur puis « Copier l’identifiant »).'; + case 'int': { + if (!/^-?\d+$/.test(value)) return 'Un nombre entier est attendu.'; + const parsed = Number.parseInt(value, 10); + if (variable.min !== undefined && parsed < variable.min) return `Minimum : ${variable.min}.`; + if (variable.max !== undefined && parsed > variable.max) return `Maximum : ${variable.max}.`; + return null; + } + case 'bool': + return value === 'true' || value === 'false' ? null : 'Valeur attendue : `true` ou `false`.'; + case 'enum': + return variable.options.includes(value) ? null : `Valeurs possibles : ${variable.options.join(', ')}.`; + case 'url': + try { + const parsed = new URL(value); + return parsed.protocol === 'http:' || parsed.protocol === 'https:' + ? null + : 'L’URL doit commencer par http:// ou https://.'; + } catch { + return 'URL invalide.'; + } + default: + if (variable.pattern && !new RegExp(variable.pattern).test(value)) return 'Format inattendu.'; + return null; + } +} + +/** Validates a whole `{ KEY: value }` map. Returns `{ KEY: message }`. */ +export function validateAll(values) { + const errors = {}; + for (const variable of VARIABLES) { + const message = validateValue(variable.key, values[variable.key] ?? ''); + if (message) errors[variable.key] = message; + } + return errors; +} + +/** Cross-field checks the per-variable rules cannot express. */ +export function crossCheck(values) { + const warnings = []; + const read = (key) => String(values[key] ?? '').trim(); + + if (read('WEB_ENABLED') === 'true') { + if (!read('WEB_PUBLIC_URL')) { + warnings.push( + 'Le tableau de bord est activé sans `WEB_PUBLIC_URL` : la connexion Discord fonctionnera, mais les liens partagés vers le site seront incomplets.', + ); + } + if (!read('DISCORD_CLIENT_SECRET')) { + warnings.push('Sans `DISCORD_CLIENT_SECRET`, seul le jeton d’amorçage permet d’ouvrir le site.'); + } + if (!read('WEB_SESSION_SECRET')) { + 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://')) { + warnings.push('`WEB_HOST=0.0.0.0` sans HTTPS expose les cookies de session en clair sur le réseau.'); + } + } + + if (read('WEBHOOK_ENABLED') === 'true' && !read('GITEA_WEBHOOK_SECRET')) { + warnings.push('Les webhooks sont activés sans secret : tous les événements Gitea seront rejetés.'); + } + + if (read('GITEA_TOKEN') && !read('GITEA_URL')) { + warnings.push('Un jeton Gitea est renseigné sans `GITEA_URL` : les appels API resteront désactivés.'); + } + + if (read('WEB_ALLOW_COMMAND_DEPLOYS') === 'true') { + warnings.push( + 'Les déploiements par commande shell sont autorisés : réserve l’accès Owner à des personnes de confiance.', + ); + } + + if (read('WEB_ENABLED') === 'true' && read('WEBHOOK_ENABLED') === 'true') { + if (read('WEB_PORT') === read('WEBHOOK_PORT')) { + warnings.push('Tableau de bord et webhooks partagent le port : un seul serveur HTTP sera démarré.'); + } + } + + return warnings; +} diff --git a/src/web/services/status-render.js b/src/web/services/status-render.js new file mode 100644 index 0000000..1fa5db5 --- /dev/null +++ b/src/web/services/status-render.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +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) => `${escape(label)}`; + +const tile = (label, value, hint) => ` +

    + ${escape(label)} + ${escape(value)} + ${hint ? `${escape(hint)}` : ''} +
    `; + +function environmentRows(environments) { + if (environments.length === 0) { + return '

    Aucun déploiement enregistré pour l’instant.

    '; + } + + return ` + + + + + ${environments + .map( + (entry) => ` + + + + + + `, + ) + .join('\n ')} + +
    EnvironnementDépôtVersionÉtatLe
    ${escape(entry.environment)}${entry.repository ? escape(entry.repository) : 'privé'}${entry.releaseTag ? `${escape(entry.releaseTag)}` : '—'}${pill(entry.tone, DEPLOY_LABELS[entry.status] ?? entry.status)}${escape(moment(entry.finishedAt))}
    `; +} + +function releaseList(releases) { + if (releases.length === 0) { + return '

    Aucune release publiée pour l’instant.

    '; + } + + return `
      + ${releases + .map((release) => { + const label = `${release.repository} · ${release.name}`; + const title = release.htmlUrl + ? `${escape(label)}` + : escape(label); + return `
    • +
      ${title}${release.prerelease ? ` ${pill('busy', 'préversion')}` : ''}
      + ${escape(moment(release.publishedAt))} +
    • `; + }) + .join('\n ')} +
    `; +} + +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 ``; +} + +/** 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 ` + + + + + + + + + État des services · FWS + + + + +
    +
    + + +
    FWSÉtat des services
    +
    + Actualisé automatiquement toutes les ${REFRESH_SECONDS} secondes +
    + +
    +

    ${escape(headline.title)}

    +

    ${escape(headline.detail)}

    +
    + +
    +

    Bot Discord

    +
    +${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)} +
    +
    + +
    +

    Déploiements

    + ${environmentRows(snapshot.environments)} +
    + +
    +

    Dernières releases

    + ${releaseList(snapshot.releases)} +
    + +

    + Relevé du . + Version lisible par une machine : /api/status. +

    + ${footer(snapshot.links)} +
    + + +`; +} diff --git a/src/web/services/status-service.js b/src/web/services/status-service.js new file mode 100644 index 0000000..8e12961 --- /dev/null +++ b/src/web/services/status-service.js @@ -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: [] }; +} diff --git a/src/web/services/wiki-render.js b/src/web/services/wiki-render.js new file mode 100644 index 0000000..5aee81e --- /dev/null +++ b/src/web/services/wiki-render.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +const document = ({ title, description, body, noindex = false }) => ` + + + + + + + + ${escape(title)} + + + + + +${body} + + +`; + +/** Sidebar: the page tree and a search box that works without scripts. */ +function sidebar(categories, currentSlug, term = '') { + const groups = categories + .map( + (category) => ` + + ${category.pages + .map( + (page) => + `${escape(page.title)}`, + ) + .join('\n ')}`, + ) + .join('\n'); + + return ` `; +} + +/** Table of contents, built from the headings the renderer collected. */ +const contents = (headings) => + headings.length < 2 + ? '' + : ` `; + +const footerLinks = () => { + const links = [ + env.links.website && `Site`, + env.links.docs && `Documentation`, + `Conditions d'utilisation`, + `Politique de confidentialité`, + ].filter(Boolean); + return `
    ${links.join(' · ')}
    `; +}; + +const shell = (categories, currentSlug, main, term) => `
    +${sidebar(categories, currentSlug, term)} +
    +${main} +${footerLinks()} +
    +
    `; + +/** 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 = `
    +
    +

    ${escape(page.category)}

    +

    ${escape(page.title)}

    + ${page.summary ? `

    ${escape(page.summary)}

    ` : ''} +
    +${html} +
    +
    + Dernière modification : + +
    +
    +${contents(headings)} +
    `; + + 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 + ? '

    Aucun résultat.

    ' + : `
      ${pages + .map( + (page) => + `
    • ${escape(page.title)}${ + page.summary ? ` — ${escape(page.summary)}` : '' + }
    • `, + ) + .join('')}
    `; + + const main = results + ? `
    +

    Recherche

    +

    ${results.length} résultat(s) pour « ${escape(term)} ».

    + ${list(results)} +
    ` + : `
    +

    Documentation FWS

    +

    Tout ce qu'il faut savoir sur le bot et l'organisation.

    + ${categories + .map((category) => `

    ${escape(category.name)}

    ${list(category.pages)}`) + .join('\n ')} +
    `; + + 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 = ` `; + + return document({ + title: 'Page introuvable · Documentation FWS', + description: 'Page introuvable.', + body: shell(categories, null, main), + noindex: true, + }); +} diff --git a/src/web/services/wiki-seed.js b/src/web/services/wiki-seed.js new file mode 100644 index 0000000..e6a04b7 --- /dev/null +++ b/src/web/services/wiki-seed.js @@ -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; +} diff --git a/src/web/setup-state.js b/src/web/setup-state.js new file mode 100644 index 0000000..f8a3f4d --- /dev/null +++ b/src/web/setup-state.js @@ -0,0 +1,32 @@ +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import { env } from '../config/env.js'; + +/** + * Bootstrap access to the configuration wizard (M16-T09). + * + * Before `.env` exists there is no Discord application to log in with, so the + * wizard accepts a single shared token: either `WEB_SETUP_TOKEN`, or one + * generated for the lifetime of `npm run setup` and printed in the console. + */ + +let runtimeToken = null; + +export function generateRuntimeSetupToken() { + runtimeToken = randomBytes(24).toString('base64url'); + return runtimeToken; +} + +export function hasSetupToken() { + return Boolean(env.web.setupToken || runtimeToken); +} + +export function isSetupTokenValid(candidate) { + const value = String(candidate ?? ''); + if (value.length === 0) return false; + + return [env.web.setupToken, runtimeToken].filter(Boolean).some((expected) => { + const a = Buffer.from(expected); + const b = Buffer.from(value); + return a.length === b.length && timingSafeEqual(a, b); + }); +} diff --git a/src/webhooks/gitea-webhook.js b/src/webhooks/gitea-webhook.js index 12dd1bc..70bae6e 100644 --- a/src/webhooks/gitea-webhook.js +++ b/src/webhooks/gitea-webhook.js @@ -5,6 +5,7 @@ import { getDatabase } from '../database/index.js'; import { logEvent } from '../database/repositories/event-log-repository.js'; import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js'; import { notify } from '../services/notifications/notification-service.js'; +import { broadcast } from '../web/events.js'; const log = createLogger('webhooks'); @@ -60,6 +61,8 @@ export async function handleGiteaWebhook(client, headers, rawBody) { payload: { deliveryId, type: notification.type }, }); + broadcast('gitea', { event, repository: payload.repository?.full_name ?? null }); + await notify(client, notification.type, { embeds: [notification.embed], content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined, diff --git a/tests/guild-settings.test.js b/tests/guild-settings.test.js new file mode 100644 index 0000000..5239790 --- /dev/null +++ b/tests/guild-settings.test.js @@ -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/); + }); +}); diff --git a/tests/projects-import.test.js b/tests/projects-import.test.js new file mode 100644 index 0000000..9b442e3 --- /dev/null +++ b/tests/projects-import.test.js @@ -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'); + }); +}); diff --git a/tests/projects.test.js b/tests/projects.test.js new file mode 100644 index 0000000..7511a50 --- /dev/null +++ b/tests/projects.test.js @@ -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); + }); +}); diff --git a/tests/tasks.test.js b/tests/tasks.test.js new file mode 100644 index 0000000..7fbf111 --- /dev/null +++ b/tests/tasks.test.js @@ -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, {}); + }); +}); diff --git a/tests/web-auth.test.js b/tests/web-auth.test.js new file mode 100644 index 0000000..17458b5 --- /dev/null +++ b/tests/web-auth.test.js @@ -0,0 +1,264 @@ +import assert from 'node:assert/strict'; +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 { + createApiToken, + getLiveApiTokenByHash, + listSessions, + revokeApiToken, +} from '../src/database/repositories/web-session-repository.js'; +import { authorize } from '../src/web/auth/guard.js'; +import { redirectUri, requestOrigin, resolveAccessLevel } from '../src/web/auth/discord-oauth.js'; +import { + assertSameOrigin, + authenticate, + closeSession, + hashToken, + openSession, +} from '../src/web/auth/session.js'; + +/** Minimal stand-ins for the Node request and response objects. */ +const fakeRequest = (headers = {}, method = 'GET') => ({ + method, + headers: { 'user-agent': 'node-test', ...headers }, + socket: { remoteAddress: '127.0.0.1' }, +}); + +function fakeResponse() { + const headers = {}; + return { + headers, + setHeader: (name, value) => { + headers[name] = value; + }, + getHeader: (name) => headers[name], + }; +} + +const cookieOf = (response) => { + const raw = [].concat(response.getHeader('Set-Cookie') ?? [])[0] ?? ''; + return raw.split(';')[0]; +}; + +describe('access guard', () => { + it('lets a public route through without an actor', () => { + assert.doesNotThrow(() => authorize(null, { public: true })); + }); + + it('refuses an anonymous caller with 401', () => { + assert.throws(() => authorize(null, { access: ACCESS_LEVELS.STAFF }), { status: 401 }); + }); + + it('compares the actor level against the route requirement', () => { + const staff = { accessLevel: ACCESS_LEVELS.STAFF, source: 'discord' }; + assert.doesNotThrow(() => authorize(staff, { access: ACCESS_LEVELS.STAFF })); + assert.throws(() => authorize(staff, { access: ACCESS_LEVELS.OWNER }), { status: 403 }); + }); + + it('defaults to Owner when a route forgets to declare its level', () => { + assert.throws(() => authorize({ accessLevel: ACCESS_LEVELS.DEV, source: 'discord' }, {}), { + status: 403, + }); + }); + + it('confines a bootstrap session to the configuration routes', () => { + const setup = { accessLevel: ACCESS_LEVELS.OWNER, source: 'setup' }; + assert.doesNotThrow(() => authorize(setup, { access: ACCESS_LEVELS.OWNER, setup: true })); + assert.throws(() => authorize(setup, { access: ACCESS_LEVELS.STAFF }), { status: 403 }); + }); +}); + +describe('cross-site protection', () => { + it('never blocks a read', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'GET'), { kind: 'session' })); + }); + + it('requires the dashboard header on a write', () => { + assert.throws(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'session' }), { status: 403 }); + assert.doesNotThrow(() => + assertSameOrigin(fakeRequest({ 'x-requested-with': 'fws-dashboard' }, 'POST'), { kind: 'session' }), + ); + }); + + it('rejects a write coming from another origin', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://evil.example', host: 'bot.example' }, + 'POST', + ); + assert.throws(() => assertSameOrigin(request, { kind: 'session' }), { status: 403 }); + }); + + it('accepts a write from the served host', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://bot.example', host: 'bot.example' }, + 'POST', + ); + assert.doesNotThrow(() => assertSameOrigin(request, { kind: 'session' })); + }); + + it('exempts machine tokens, which carry no cookie', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'api-token' })); + }); +}); + +describe('dashboard sessions', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_sessions; DELETE FROM web_api_tokens;')); + + const login = (level = ACCESS_LEVELS.DEV) => { + const response = fakeResponse(); + const session = openSession(fakeRequest(), response, { + user: { id: '42', username: 'kim', displayName: 'Kim', avatar: null }, + accessLevel: level, + }); + return { session, cookie: cookieOf(response) }; + }; + + it('stores only the hash of the cookie value', () => { + const { session, cookie } = login(); + const token = decodeURIComponent(cookie.split('=')[1]); + + assert.notEqual(session.token_hash, token); + assert.equal(session.token_hash, hashToken(token)); + }); + + it('identifies the caller from its cookie', () => { + const { cookie } = login(ACCESS_LEVELS.STAFF); + const actor = authenticate(fakeRequest({ cookie })); + + assert.equal(actor.kind, 'session'); + assert.equal(actor.userId, '42'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.STAFF); + }); + + it('returns null for an unknown or absent cookie', () => { + assert.equal(authenticate(fakeRequest()), null); + assert.equal(authenticate(fakeRequest({ cookie: 'fws_session=inventé' })), null); + }); + + it('ignores an expired session', () => { + const { cookie } = login(); + getDatabase().exec("UPDATE web_sessions SET expires_at = datetime('now', '-1 hour')"); + assert.equal(authenticate(fakeRequest({ cookie })), null); + }); + + it('closes a session and clears the cookie', () => { + const { cookie } = login(); + const response = fakeResponse(); + closeSession(fakeRequest({ cookie }), response); + + assert.equal(authenticate(fakeRequest({ cookie })), null); + assert.match([].concat(response.getHeader('Set-Cookie'))[0], /Max-Age=0/); + }); + + it('lists the live sessions', () => { + login(); + login(ACCESS_LEVELS.OWNER); + assert.equal(listSessions().length, 2); + }); +}); + +describe('api tokens', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_api_tokens;')); + + const issue = () => { + const token = 'fws_test-token-value'; + const id = createApiToken({ + name: 'ci', + tokenHash: hashToken(token), + prefix: token.slice(0, 12), + accessLevel: ACCESS_LEVELS.DEV, + }); + return { id, token }; + }; + + it('authenticates a bearer token', () => { + const { token } = issue(); + const actor = authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + + assert.equal(actor.kind, 'api-token'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.DEV); + }); + + it('records the last usage', () => { + const { token } = issue(); + authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + assert.ok(getLiveApiTokenByHash(hashToken(token)).last_used_at); + }); + + it('refuses a revoked token', () => { + const { id, token } = issue(); + revokeApiToken(id); + assert.equal(authenticate(fakeRequest({ authorization: `Bearer ${token}` })), null); + }); + + it('refuses an unknown token', () => { + assert.equal(authenticate(fakeRequest({ authorization: 'Bearer nope' })), null); + }); +}); + +describe('oauth access level', () => { + const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' }; + + it('gives Owner to the guild owner whatever their roles', () => { + const level = resolveAccessLevel({ member: { roles: [] }, userId: '1', guildOwnerId: '1', roles }); + assert.equal(level, ACCESS_LEVELS.OWNER); + }); + + it('reads the highest matching role', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['r-staff', 'r-dev'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.DEV, + ); + }); + + it('falls back to plain member', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['autre'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.USER, + ); + }); + + it('returns null when the visitor is not in the guild', () => { + assert.equal(resolveAccessLevel({ member: null, userId: '2', guildOwnerId: '1', roles }), null); + }); +}); + +describe('oauth redirect', () => { + it('follows the address the visitor actually used', () => { + // A hosting panel can publish the site on another port than the one + // announced by `WEB_PUBLIC_URL`; the browser's address is what Discord + // compares against. + const request = fakeRequest({ host: 'bot.example:25571' }); + assert.equal(requestOrigin(request), 'http://bot.example:25571'); + assert.equal(redirectUri(request), 'http://bot.example:25571/auth/callback'); + }); + + it('honours a reverse proxy', () => { + const request = fakeRequest({ + host: '127.0.0.1:3080', + 'x-forwarded-host': 'bot.example', + 'x-forwarded-proto': 'https', + }); + assert.equal(redirectUri(request), 'https://bot.example/auth/callback'); + }); + + it('keeps only the left-most forwarded value', () => { + const request = fakeRequest({ + host: 'interne:3080', + 'x-forwarded-host': 'bot.example, interne', + 'x-forwarded-proto': 'https, http', + }); + assert.equal(requestOrigin(request), 'https://bot.example'); + }); + + it('falls back to the configured URL when there is no request', () => { + // `WEB_PUBLIC_URL` is unset in the tests, so nothing can be built. + assert.equal(requestOrigin(undefined), ''); + assert.equal(redirectUri(undefined), ''); + }); +}); diff --git a/tests/web-configuration.test.js b/tests/web-configuration.test.js new file mode 100644 index 0000000..a4953e2 --- /dev/null +++ b/tests/web-configuration.test.js @@ -0,0 +1,208 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { + diffValues, + maskValues, + mergeValues, + parseEnv, + renderEnvFile, + secretStatus, + writeEnvFile, +} from '../src/web/services/env-file.js'; +import { + BY_KEY, + SECTIONS, + VARIABLES, + crossCheck, + requiredKeys, + validateAll, + validateValue, +} from '../src/web/services/env-schema.js'; + +describe('env schema', () => { + it('declares every variable inside a known section', () => { + const sectionIds = new Set(SECTIONS.map((section) => section.id)); + for (const variable of VARIABLES) { + assert.ok(sectionIds.has(variable.section), `${variable.key} points at an unknown section`); + } + }); + + it('documents every variable with a label and a help text', () => { + for (const variable of VARIABLES) { + assert.ok(variable.label?.length > 0, `${variable.key} has no label`); + assert.ok(variable.help?.length > 0, `${variable.key} has no help`); + } + }); + + it('covers the variables the bot refuses to start without', () => { + assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']); + }); + + it('mirrors the keys used by .env.example', () => { + const example = parseEnv(readFileSync('.env.example', 'utf8')); + for (const key of Object.keys(example)) { + assert.ok(key in BY_KEY, `${key} is in .env.example but missing from the schema`); + } + for (const variable of VARIABLES) { + assert.ok(variable.key in example, `${variable.key} is in the schema but missing from .env.example`); + } + }); + + it('validates Discord identifiers', () => { + assert.equal(validateValue('DISCORD_GUILD_ID', '123456789012345678'), null); + assert.match(validateValue('DISCORD_GUILD_ID', 'abc'), /17 à 20 chiffres/); + }); + + it('validates numbers against their bounds', () => { + assert.equal(validateValue('WEB_PORT', '3080'), null); + assert.match(validateValue('WEB_PORT', '99999'), /Maximum/); + assert.match(validateValue('WEB_PORT', 'abc'), /nombre entier/); + }); + + it('validates booleans, enums and urls', () => { + assert.equal(validateValue('WEB_ENABLED', 'true'), null); + assert.match(validateValue('WEB_ENABLED', 'oui'), /true` ou `false/); + assert.equal(validateValue('LOG_LEVEL', 'debug'), null); + assert.match(validateValue('LOG_LEVEL', 'verbose'), /Valeurs possibles/); + assert.equal(validateValue('GITEA_URL', 'https://gitea.example.org'), null); + assert.match(validateValue('GITEA_URL', 'gitea.example.org'), /URL invalide/); + }); + + it('accepts an empty optional value but not an empty required one', () => { + assert.equal(validateValue('ROLE_OWNER_ID', ''), null); + assert.match(validateValue('DISCORD_TOKEN', ''), /obligatoire/); + }); + + it('reports every invalid key at once', () => { + const errors = validateAll({ DISCORD_TOKEN: 'x', DISCORD_CLIENT_ID: 'nope', DISCORD_GUILD_ID: '' }); + assert.ok(errors.DISCORD_CLIENT_ID); + assert.ok(errors.DISCORD_GUILD_ID); + assert.equal(errors.DISCORD_TOKEN, undefined); + }); + + it('warns about combinations no single field can catch', () => { + const warnings = crossCheck({ WEBHOOK_ENABLED: 'true', GITEA_WEBHOOK_SECRET: '' }); + 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', () => { + const warnings = crossCheck({ + WEB_ENABLED: 'true', + WEB_HOST: '0.0.0.0', + WEB_PUBLIC_URL: 'http://bot.example.org', + DISCORD_CLIENT_SECRET: 'x', + WEB_SESSION_SECRET: 'y', + }); + assert.ok(warnings.some((warning) => warning.includes('en clair'))); + }); +}); + +describe('env file', () => { + let directory; + let file; + + before(() => { + directory = mkdtempSync(path.join(tmpdir(), 'fws-env-')); + file = path.join(directory, '.env'); + }); + after(() => rmSync(directory, { recursive: true, force: true })); + + it('parses quoted, unquoted and commented lines', () => { + const values = parseEnv('# comment\nA=1\nB="deux mots"\nC=\'trois\'\nexport D=4\ninvalid\n'); + assert.deepEqual(values, { A: '1', B: 'deux mots', C: 'trois', D: '4' }); + }); + + it('renders a file that documents every variable', () => { + const content = renderEnvFile({ DISCORD_TOKEN: 'secret', WEB_PORT: '3080' }); + for (const variable of VARIABLES) { + assert.ok(content.includes(`${variable.key}=`), `${variable.key} is missing from the rendered file`); + assert.ok(content.includes(variable.label), `${variable.label} is missing from the rendered file`); + } + }); + + it('keeps variables it does not know about', () => { + const content = renderEnvFile({}, { CUSTOM_THING: 'valeur' }); + assert.match(content, /CUSTOM_THING=valeur/); + }); + + it('quotes values that need it', () => { + const content = renderEnvFile({ GITEA_OWNER: 'deux mots' }); + assert.match(content, /GITEA_OWNER="deux mots"/); + }); + + it('writes the file with 600 permissions and backs up the previous one', () => { + writeFileSync(file, 'DISCORD_TOKEN=ancien\n'); + const result = writeEnvFile({ DISCORD_TOKEN: 'nouveau' }, { file }); + + assert.ok(result.backup, 'no backup was made'); + assert.match(readFileSync(result.backup, 'utf8'), /ancien/); + assert.match(readFileSync(file, 'utf8'), /DISCORD_TOKEN=nouveau/); + assert.equal(statSync(file).mode & 0o777, 0o600); + }); + + it('keeps the stored secret when the submitted one is empty', () => { + const merged = mergeValues( + { DISCORD_TOKEN: 'garde-moi', GITEA_OWNER: 'FWS' }, + { DISCORD_TOKEN: '', GITEA_OWNER: 'AUTRE' }, + ); + assert.equal(merged.DISCORD_TOKEN, 'garde-moi'); + assert.equal(merged.GITEA_OWNER, 'AUTRE'); + }); + + it('ignores keys that are not part of the schema', () => { + const merged = mergeValues({}, { NOT_A_REAL_KEY: 'x' }); + assert.equal(merged.NOT_A_REAL_KEY, undefined); + }); + + it('never sends a secret back to the browser', () => { + const masked = maskValues({ DISCORD_TOKEN: 'tres-secret', GITEA_OWNER: 'FWS' }); + assert.equal(masked.DISCORD_TOKEN, ''); + assert.equal(masked.GITEA_OWNER, 'FWS'); + + const status = secretStatus({ DISCORD_TOKEN: 'tres-secret' }); + assert.equal(status.DISCORD_TOKEN, true); + assert.equal(status.GITEA_TOKEN, false); + }); + + it('describes a change without revealing the secret', () => { + const diff = diffValues( + { DISCORD_TOKEN: 'avant', WEB_PORT: '3080' }, + { DISCORD_TOKEN: 'apres', WEB_PORT: '4000' }, + ); + const token = diff.find((entry) => entry.key === 'DISCORD_TOKEN'); + + assert.equal(token.before, '••••••'); + assert.equal(token.after, '••••••'); + assert.equal(token.restartRequired, true); + + const port = diff.find((entry) => entry.key === 'WEB_PORT'); + assert.equal(port.after, '4000'); + }); +}); diff --git a/tests/web-deployments.test.js b/tests/web-deployments.test.js new file mode 100644 index 0000000..71a0105 --- /dev/null +++ b/tests/web-deployments.test.js @@ -0,0 +1,224 @@ +import assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { createServer } from 'node:http'; +import { after, afterEach, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + countByStatus, + createTarget, + getTarget, + listAutoTargets, + listDeployments, + listTargets, + removeTarget, + updateTarget, +} from '../src/database/repositories/deploy-repository.js'; +import { splitRepository } from '../src/services/gitea/gitea-admin.js'; +import { assertRunnable, describeTarget, runDeployment } from '../src/web/services/deploy-service.js'; + +const GUILD = 'guild-1'; + +const webhookTarget = (overrides = {}) => + createTarget({ + guildId: GUILD, + name: 'production', + repository: 'FWS/FWS-Arch', + environment: 'production', + kind: 'webhook', + config: { url: 'http://127.0.0.1:1/hook', secret: 'partage' }, + ...overrides, + }); + +describe('deploy repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('stores and reads back a target with its parsed config', () => { + const target = webhookTarget(); + assert.equal(target.config.url, 'http://127.0.0.1:1/hook'); + assert.equal(target.enabled, true); + assert.equal(target.auto_deploy, false); + assert.deepEqual(getTarget(target.id), target); + }); + + it('filters targets by repository', () => { + webhookTarget(); + webhookTarget({ name: 'site', repository: 'FWS/site' }); + + assert.equal(listTargets({ guildId: GUILD }).length, 2); + assert.equal(listTargets({ guildId: GUILD, repository: 'FWS/site' }).length, 1); + }); + + it('only returns enabled auto-deploy targets', () => { + webhookTarget({ name: 'manuel' }); + webhookTarget({ name: 'auto', autoDeploy: true }); + webhookTarget({ name: 'auto-en-pause', autoDeploy: true, enabled: false }); + + const auto = listAutoTargets({ guildId: GUILD, repository: 'FWS/FWS-Arch' }); + assert.deepEqual( + auto.map((target) => target.name), + ['auto'], + ); + }); + + it('updates only the known columns', () => { + const target = webhookTarget(); + // The repository speaks in column names; the API layer does the translation. + const updated = updateTarget(target.id, { environment: 'staging', bogus: 'ignoré', auto_deploy: true }); + + assert.equal(updated.environment, 'staging'); + assert.equal(updated.auto_deploy, true); + assert.equal(updated.bogus, undefined); + assert.ok(updated.updated_at); + }); + + it('keeps the history when its target is deleted', async () => { + const target = webhookTarget(); + await runDeployment(null, target, { ref: 'main' }).catch(() => null); + removeTarget(target.id); + + const [deployment] = listDeployments({ guildId: GUILD }); + assert.equal(deployment.target_id, null); + assert.equal(deployment.target_name, 'production'); + }); + + it('describes a target in one line', () => { + assert.match(describeTarget(webhookTarget()), /^POST http/); + assert.equal( + describeTarget({ kind: 'gitea-action', config: { workflow: 'deploy.yml', ref: 'main' } }), + 'workflow deploy.yml sur main', + ); + }); +}); + +describe('deploy guards', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses a disabled target', () => { + assert.throws(() => assertRunnable(webhookTarget({ enabled: false })), { status: 400 }); + }); + + it('refuses a webhook target with no url', () => { + assert.throws(() => assertRunnable(webhookTarget({ config: {} })), { status: 400 }); + }); + + it('refuses a command target while command deploys are off', () => { + const target = webhookTarget({ name: 'shell', kind: 'command', config: { command: 'echo bonjour' } }); + // `WEB_ALLOW_COMMAND_DEPLOYS` is unset in the tests, so this must be blocked. + assert.throws(() => assertRunnable(target), { status: 403 }); + }); + + it('refuses an unknown kind', () => { + assert.throws(() => assertRunnable({ enabled: true, kind: 'magic', config: {} }), { status: 400 }); + }); +}); + +describe('webhook deployments', () => { + let server; + let received; + let reply; + + before(async () => { + initDatabase(':memory:'); + server = createServer((request, response) => { + let body = ''; + request.on('data', (chunk) => (body += chunk)); + request.on('end', () => { + received = { headers: request.headers, body }; + response.writeHead(reply.status, { 'Content-Type': 'text/plain' }).end(reply.body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + }); + + after(async () => { + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => { + getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'); + received = null; + reply = { status: 200, body: 'déployé' }; + }); + afterEach(() => { + received = null; + }); + + const url = () => `http://127.0.0.1:${server.address().port}/hook`; + + it('calls the webhook and records a success', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + const deployment = await runDeployment(null, target, { releaseTag: 'v1.0.0', triggeredBy: 'u1' }); + + assert.equal(deployment.status, 'success'); + assert.match(deployment.log, /déployé/); + + const [stored] = listDeployments({ guildId: 'guild-1' }); + assert.equal(stored.status, 'success'); + assert.equal(stored.release_tag, 'v1.0.0'); + assert.ok(stored.finished_at); + }); + + it('signs the payload with the shared secret', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + await runDeployment(null, target, { ref: 'main' }); + + const expected = createHmac('sha256', 'partage').update(received.body).digest('hex'); + assert.equal(received.headers['x-fws-signature'], expected); + }); + + it('sends the deployment context in the body', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, { releaseTag: 'v2.0.0', ref: 'main', triggeredBy: 'u9' }); + + const payload = JSON.parse(received.body); + assert.equal(payload.repository, 'FWS/FWS-Arch'); + assert.equal(payload.environment, 'production'); + assert.equal(payload.releaseTag, 'v2.0.0'); + assert.equal(payload.triggeredBy, 'u9'); + }); + + it('omits the signature when no secret is configured', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, {}); + assert.equal(received.headers['x-fws-signature'], undefined); + }); + + it('records a failure when the endpoint answers with an error', async () => { + reply = { status: 500, body: 'boum' }; + const target = webhookTarget({ config: { url: url() } }); + const deployment = await runDeployment(null, target, {}); + + assert.equal(deployment.status, 'failed'); + assert.match(deployment.error, /500/); + assert.match(deployment.log, /boum/); + }); + + it('counts the deployments by status', async () => { + const ok = webhookTarget({ name: 'ok', config: { url: url() } }); + await runDeployment(null, ok, {}); + reply = { status: 503, body: '' }; + await runDeployment(null, ok, {}); + + const counts = Object.fromEntries(countByStatus('guild-1').map((row) => [row.status, row.count])); + assert.equal(counts.success, 1); + assert.equal(counts.failed, 1); + }); +}); + +describe('repository names', () => { + it('splits a full name', () => { + assert.deepEqual(splitRepository('FWS/FWS-Arch'), { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('rejects anything that is not exactly owner/repo', () => { + assert.equal(splitRepository('FWS'), null); + assert.equal(splitRepository('FWS/Arch/extra'), null); + assert.equal(splitRepository(''), null); + assert.equal(splitRepository(undefined), null); + }); +}); diff --git a/tests/web-events.test.js b/tests/web-events.test.js new file mode 100644 index 0000000..cd6bf8c --- /dev/null +++ b/tests/web-events.test.js @@ -0,0 +1,187 @@ +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 { createApiToken } from '../src/database/repositories/web-session-repository.js'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { hashToken } from '../src/web/auth/session.js'; +import { broadcast, closeEventStreams, subscriberCount, topicForPath } from '../src/web/events.js'; +import { createHandler } from '../src/web/server.js'; + +/** Live updates pushed over server-sent events (M16-T12). */ + +const TOKEN = 'fws_events-test-token'; + +/** Reads SSE frames off the socket until `stop()` is called. */ +function openStream(url) { + const controller = new AbortController(); + const frames = []; + let resolveReady; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + const done = fetch(url, { + headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'text/event-stream' }, + signal: controller.signal, + }).then(async (response) => { + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/event-stream/); + resolveReady(response); + + const decoder = new TextDecoder(); + try { + for await (const chunk of response.body) frames.push(decoder.decode(chunk, { stream: true })); + } catch { + // Aborting the request is how the test ends the stream. + } + }); + + return { ready, frames, stop: () => controller.abort(), done }; +} + +/** Events land asynchronously; give the socket a moment to deliver. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 120)); + +describe('event topics', () => { + it('routes a write to the pages that care about it', () => { + assert.equal(topicForPath('/api/deploy/targets/3/run'), 'deployments'); + assert.equal(topicForPath('/api/deployments'), 'deployments'); + assert.equal(topicForPath('/api/repositories/FWS/Arch/issues'), 'gitea'); + assert.equal(topicForPath('/api/organization'), 'gitea'); + assert.equal(topicForPath('/api/discord/announce'), 'discord'); + assert.equal(topicForPath('/api/community/tickets/1/close'), 'community'); + assert.equal(topicForPath('/api/settings/values/x'), 'settings'); + assert.equal(topicForPath('/api/auth/logout'), 'mutation'); + }); + + it('does nothing when nobody is listening', () => { + assert.equal(broadcast('tick', {}), 0); + }); +}); + +describe('event stream', () => { + let server; + let base; + + before(async () => { + initDatabase(':memory:'); + createApiToken({ + name: 'events', + tokenHash: hashToken(TOKEN), + prefix: TOKEN.slice(0, 12), + accessLevel: ACCESS_LEVELS.OWNER, + }); + + server = createServer(createHandler({ client: null, setupOnly: false })); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + base = `http://127.0.0.1:${server.address().port}`; + }); + + after(async () => { + closeEventStreams(); + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses an anonymous listener', async () => { + const response = await fetch(`${base}/api/events`); + assert.equal(response.status, 401); + }); + + it('greets a subscriber and counts it', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(subscriberCount(), 1); + assert.match(stream.frames.join(''), /event: ready/); + assert.match(stream.frames.join(''), /retry: 5000/); + + stream.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); + + it('pushes a broadcast to the open streams', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(broadcast('deployments', { id: 7, status: 'running' }), 1); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"id":7/); + assert.match(received, /"topic":"deployments"/); + + stream.stop(); + await settle(); + }); + + it('announces a successful write, and only once it succeeded', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + const write = (body) => + fetch(`${base}/api/deploy/targets`, { + method: 'POST', + headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + const rejected = await write({ name: '', repository: 'nope', kind: 'webhook' }); + assert.equal(rejected.status, 400); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + const accepted = await write({ + name: 'production', + repository: 'FWS/FWS-Arch', + kind: 'webhook', + config: { url: 'https://deploy.example/hook' }, + }); + assert.equal(accepted.status, 200); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"method":"POST"/); + + stream.stop(); + await settle(); + }); + + it('stays silent on a read', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + await fetch(`${base}/api/deployments`, { headers: { Authorization: `Bearer ${TOKEN}` } }); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + stream.stop(); + await settle(); + }); + + it('serves several dashboards at once', async () => { + const first = openStream(`${base}/api/events`); + const second = openStream(`${base}/api/events`); + await Promise.all([first.ready, second.ready]); + await settle(); + + assert.equal(broadcast('gitea', { event: 'push' }), 2); + await settle(); + + assert.match(first.frames.join(''), /event: gitea/); + assert.match(second.frames.join(''), /event: gitea/); + + first.stop(); + second.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); +}); diff --git a/tests/web-nav.test.js b/tests/web-nav.test.js new file mode 100644 index 0000000..7aed963 --- /dev/null +++ b/tests/web-nav.test.js @@ -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')); + }); +}); diff --git a/tests/web-palette.test.js b/tests/web-palette.test.js new file mode 100644 index 0000000..0c5377d --- /dev/null +++ b/tests/web-palette.test.js @@ -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'), []); + }); +}); diff --git a/tests/web-router.test.js b/tests/web-router.test.js new file mode 100644 index 0000000..3b75ed5 --- /dev/null +++ b/tests/web-router.test.js @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { createRouter } from '../src/web/router.js'; + +const noop = () => null; + +describe('web router', () => { + const router = createRouter(); + router.get('/api/health', noop, { public: true }); + router.get('/api/repositories/:owner/:repo', noop); + router.post('/api/repositories/:owner/:repo/issues', noop); + router.delete('/api/repositories/:owner/:repo/branches', noop); + + it('matches a static route', () => { + const route = router.resolve('GET', '/api/health'); + assert.deepEqual(route.params, {}); + assert.equal(route.options.public, true); + }); + + it('extracts named parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/FWS-Arch'); + assert.deepEqual(route.params, { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('decodes percent-encoded parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/mon%20depot'); + assert.equal(route.params.repo, 'mon depot'); + }); + + it('keeps methods apart on the same path', () => { + assert.doesNotThrow(() => router.resolve('DELETE', '/api/repositories/FWS/Arch/branches')); + assert.throws(() => router.resolve('GET', '/api/repositories/FWS/Arch/branches'), { status: 405 }); + }); + + it('rejects an unknown path with 404', () => { + assert.throws(() => router.resolve('GET', '/api/nope'), { status: 404 }); + }); + + it('does not let a shorter path match a longer pattern', () => { + assert.throws(() => router.resolve('GET', '/api/repositories/FWS'), { status: 404 }); + }); + + it('lists the registered routes', () => { + assert.ok(router.list().includes('POST /api/repositories/:owner/:repo/issues')); + }); +}); diff --git a/tests/web-search.test.js b/tests/web-search.test.js new file mode 100644 index 0000000..7edc94d --- /dev/null +++ b/tests/web-search.test.js @@ -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); + }); +}); diff --git a/tests/web-server.test.js b/tests/web-server.test.js new file mode 100644 index 0000000..48c4505 --- /dev/null +++ b/tests/web-server.test.js @@ -0,0 +1,207 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, describe, it } from 'node:test'; +import { closeDatabase, initDatabase } from '../src/database/index.js'; +import { createHandler } from '../src/web/server.js'; +import { generateRuntimeSetupToken } from '../src/web/setup-state.js'; + +/** Drives the real request handler over a loopback socket (M16-T01). */ +function serve(options) { + const server = createServer(createHandler(options)); + const ready = new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + + return { + ready, + close: () => new Promise((resolve) => server.close(resolve)), + url: (path) => `http://127.0.0.1:${server.address().port}${path}`, + fetch: (path, init) => fetch(`http://127.0.0.1:${server.address().port}${path}`, init), + }; +} + +const WRITE_HEADERS = { 'Content-Type': 'application/json', 'X-Requested-With': 'fws-dashboard' }; + +describe('dashboard server', () => { + let app; + + before(async () => { + initDatabase(':memory:'); + app = serve({ client: null, setupOnly: false }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('answers the health probe without a session', async () => { + const response = await app.fetch('/api/health'); + const body = await response.json(); + + assert.equal(response.status, 200); + assert.equal(body.status, 'starting'); + assert.equal(body.setupOnly, false); + }); + + it('describes how to sign in without a session', async () => { + const body = await app.fetch('/api/auth/config').then((response) => response.json()); + assert.equal(typeof body.oauthConfigured, 'boolean'); + assert.equal(body.loginUrl, '/auth/login'); + }); + + it('reports an anonymous visitor as not authenticated', async () => { + const body = await app.fetch('/api/me').then((response) => response.json()); + assert.equal(body.authenticated, false); + }); + + it('refuses a protected route with 401', async () => { + const response = await app.fetch('/api/overview'); + assert.equal(response.status, 401); + assert.match((await response.json()).error, /Authentification/); + }); + + it('returns 404 on an unknown API route', async () => { + assert.equal((await app.fetch('/api/nope')).status, 404); + }); + + it('returns 405 when the path exists under another method', async () => { + const response = await app.fetch('/api/health', { method: 'POST', headers: WRITE_HEADERS, body: '{}' }); + assert.equal(response.status, 405); + }); + + it('blocks a write that does not carry the dashboard header', async () => { + const response = await app.fetch('/api/auth/logout', { method: 'POST' }); + assert.equal(response.status, 403); + assert.match((await response.json()).error, /X-Requested-With/); + }); + + it('serves the single page application shell', async () => { + const response = await app.fetch('/'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/html/); + assert.match(body, /
    { + const response = await app.fetch('/repos/FWS/FWS-Arch'); + assert.equal(response.status, 200); + assert.match(await response.text(), /
    { + const response = await app.fetch('/core/dom.js'); + assert.equal(response.status, 200); + 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 () => { + const response = await app.fetch('/'); + assert.equal(response.headers.get('x-frame-options'), 'DENY'); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + assert.match(response.headers.get('content-security-policy'), /frame-ancestors 'none'/); + }); + + it('never serves a file outside the public directory', async () => { + // The path is normalised server side, so the traversal lands on the shell. + const response = await app.fetch('/..%2f..%2fpackage.json'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.doesNotMatch(body, /"fws-discordbot"/); + }); + + it('rejects a malformed JSON body', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: 'pas du json', + }); + assert.equal(response.status, 400); + }); +}); + +describe('bootstrap mode', () => { + let app; + let token; + + before(async () => { + initDatabase(':memory:'); + token = generateRuntimeSetupToken(); + app = serve({ client: null, setupOnly: true }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('announces itself as a setup-only server', async () => { + const body = await app.fetch('/api/health').then((response) => response.json()); + assert.equal(body.setupOnly, true); + }); + + it('does not even register the dashboard routes', async () => { + assert.equal((await app.fetch('/api/overview')).status, 404); + assert.equal((await app.fetch('/api/settings')).status, 404); + }); + + it('refuses a wrong bootstrap token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token: 'mauvais' }), + }); + assert.equal(response.status, 403); + }); + + it('opens a confined session with the right token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token }), + }); + assert.equal(response.status, 200); + + const cookie = response.headers.getSetCookie()[0].split(';')[0]; + const me = await app.fetch('/api/me', { headers: { cookie } }).then((r) => r.json()); + assert.equal(me.source, 'setup'); + + const configuration = await app.fetch('/api/configuration', { headers: { cookie } }); + assert.equal(configuration.status, 200); + assert.ok((await configuration.json()).sections.length > 0); + }); + + it('serves the wizard front-end', async () => { + const response = await app.fetch('/views/setup.js'); + assert.equal(response.status, 200); + }); +}); diff --git a/tests/web-status-disabled.test.js b/tests/web-status-disabled.test.js new file mode 100644 index 0000000..53c16b5 --- /dev/null +++ b/tests/web-status-disabled.test.js @@ -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); + }); +}); diff --git a/tests/web-status.test.js b/tests/web-status.test.js new file mode 100644 index 0000000..40d88cc --- /dev/null +++ b/tests/web-status.test.js @@ -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()), /'); + assert.doesNotMatch(html, /