13 Commits
Author SHA1 Message Date
BlackAngelTV 4d219eaa18 fix(ci): keep packaging files and shebang noise out of the shell scan
security / secrets (push) Successful in 14s
security / dependencies (push) Failing after 30s
CI / quality (push) Failing after 52s
security / shell (push) Successful in 7s
security / sast (push) Successful in 2m21s
2026-12-06 18:47:35 +01:00
BlackAngelTV 325e38d905 ci(security): add secret, dependency, shell and injection scans
security / secrets (push) Successful in 24s
CI / quality (push) Failing after 47s
security / shell (push) Successful in 4s
security / sast (push) Successful in 27s
security / dependencies (push) Failing after 53s
2026-12-06 18:40:26 +01:00
BlackAngelTV 3b10543f83 ci: drop the runner probe 2026-12-06 18:40:26 +01:00
BlackAngelTV 701257bc36 ci: probe runner capabilities 2026-12-06 18:40:26 +01:00
BlackAngelTV a08ed3b10e chore(security): allowlist template and test placeholders 2026-12-06 18:40:26 +01:00
BlackAngelTV 4bb75d68e3 ci(security): scan secrets, dependencies and shell scripts 2026-12-06 18:40:26 +01:00
BlackAngelTV adc96e4d75 feat(gitea): use a dedicated admin token for recruitment
CI / quality (push) Failing after 45s
Recruitment needs `write:admin` and `write:organization`, which the everyday
token must not carry. A second token keeps the repository and issue scopes
least privileged, falls back to `GITEA_TOKEN` so existing installs keep
working, and a 403 now names the missing scope instead of pretending Gitea
did not answer.
2026-12-06 18:01:43 +01:00
BlackAngelTV 9b45c9bf89 feat(gitea): require a reason when the team refuses an application
CI / quality (push) Failing after 58s
A refusal without a reason leaves the member guessing why, which makes the
recruitment feel arbitrary. The reject button now opens a modal, the reason is
stored with the application, added to the review message and sent verbatim in
the DM; when the DM cannot be delivered, the team gets it back to pass along.
2026-12-06 17:18:11 +01:00
BlackAngelTV 6f3ec439d4 feat(gitea): recruit developers from a Discord panel into FWS
Recruited people need a Gitea account without a public signup on the forge.
The panel posts in its own Gitea category, the single modal keeps the whole
application in one gesture, and acceptance creates a restricted account in the
FWS organization, adds it to the Dev team, grants the Discord Dev role and
sends the temporary password by DM. Restrictions keep the new account working
inside the organization only, with no personal repository of its own.
2026-12-06 17:17:05 +01:00
BlackAngelTV ed14b8260c feat(tickets): open tickets from a panel button in any channel
CI / quality (push) Has been cancelled
Members had to know `/ticket create` and its category list to reach support,
so the entry point is now a panel: `/ticket setup` publishes it in the current
channel, the button opens a menu of the categories the member is allowed to
open, and the choice creates the ticket.

The panel channel and message are stored in `ticket_panels`, so a reinstall
replaces the previous message instead of leaving the server two entry points,
and the panel survives a restart.
2026-10-02 20:29:22 +02:00
BlackAngelTV 1310840215 feat(tickets): guide members in ticket channels and log to the technical salon
CI / quality (push) Has been cancelled
Tickets were opened with three words and members expected an immediate answer,
so the channel now posts a guidance embed: what details to give (context, steps
to reproduce, exact error, OS version) and that a reply can take a while.

The ticket journal moves to CHANNEL_LOGS_ID so the environment keeps one log
salon per purpose: CHANNEL_TICKETS_LOGS_ID held the same entries and nothing
else read it. A wrong CATEGORY_TICKETS_ID now says which case it is, since a
missing category was reported as a mistyped one.
2026-10-02 20:13:31 +02:00
BlackAngelTV a996065861 Merge pull request 'Feat/dashboard rules' (#150) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #150
2026-09-25 19:16:10 +00:00
BlackAngelTV 4e0f43eace Merge pull request 'Feat/dashboard rules' (#149) from feat/dashboard-rules into main
CI / quality (push) Has been cancelled
Reviewed-on: #149
2026-09-25 18:50:41 +00:00
26 changed files with 2308 additions and 60 deletions

No files matched your search

+9 -1
View File
@@ -33,7 +33,6 @@ CHANNEL_RULES_ID=
CHANNEL_ANNOUNCEMENTS_ID=
CHANNEL_LOGS_ID=
CHANNEL_MOD_LOGS_ID=
CHANNEL_TICKETS_LOGS_ID=
CHANNEL_NOTIF_ISSUES_ID=
CHANNEL_NOTIF_PULL_REQUESTS_ID=
CHANNEL_NOTIF_COMMITS_ID=
@@ -41,6 +40,8 @@ CHANNEL_NOTIF_RELEASES_ID=
CHANNEL_NOTIF_ERRORS_ID=
# Category under which private ticket channels are created (M6)
CATEGORY_TICKETS_ID=
# Où le bot publie les candidatures Gitea (repli : CHANNEL_LOGS_ID)
CHANNEL_GITEA_APPLICATIONS_ID=
# --- Salons vocaux temporaires (M14) ----------------------------------------
# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire
@@ -58,8 +59,15 @@ BOT_STATUS_INTERVAL_SECONDS=60
GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it.
GITEA_TOKEN=
# Admin token for the recruitment flow (write:admin, write:organization, read:user).
# Leave empty to fall back to GITEA_TOKEN.
GITEA_RECRUITMENT_TOKEN=
GITEA_OWNER=FWS
GITEA_REPO=FWS-Arch
# Organisation qui accueille les personnes recrutées (défaut : GITEA_OWNER)
GITEA_ORG=FWS
# Équipe de l'organisation où elles sont ajoutées à l'acceptation
GITEA_DEV_TEAM=Dev
GITEA_TIMEOUT_MS=10000
GITEA_MAX_RETRIES=2
+137
View File
@@ -0,0 +1,137 @@
name: security
# Shared security gate for FWS repositories: leaked credentials, known
# vulnerabilities in the dependencies, shell injection patterns and, through
# opengrep, the language level injection rules (SQL, command, template, XSS).
# Every tool is a static binary downloaded at run time so the job does not
# depend on what the runner image happens to ship.
on:
push:
pull_request:
schedule:
- cron: '0 4 * * 1'
workflow_dispatch:
permissions:
contents: read
env:
GITLEAKS_VERSION: '8.28.0'
OSV_SCANNER_VERSION: '2.7.1'
SHELLCHECK_VERSION: '0.10.0'
OPENGREP_VERSION: '2.1.0'
jobs:
secrets:
name: secrets
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# `dir` scans the checkout rather than the history: a credential that was
# removed from the tree must not keep the gate red forever, and the tree
# is what a pull request introduces. A repository that needs to allowlist
# fixtures ships a .gitleaks.toml next to this file.
- name: Scan the tree for credentials
run: |
set -euo pipefail
curl -fsSL -o "$RUNNER_TEMP/gitleaks.tgz" \
"https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"
tar -xzf "$RUNNER_TEMP/gitleaks.tgz" -C "$RUNNER_TEMP" gitleaks
config=()
[ -f .gitleaks.toml ] && config=(--config .gitleaks.toml)
"$RUNNER_TEMP/gitleaks" dir . --no-banner --redact --verbose --exit-code 1 "${config[@]}"
dependencies:
name: dependencies
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# OSV reads the lockfiles it recognises (npm, pip, Go, Cargo, Composer…)
# and answers from osv.dev. A repository without a lockfile passes instead
# of failing, so the same workflow fits every stack in the organisation.
- name: Scan dependencies for known vulnerabilities
run: |
set -euo pipefail
curl -fsSL -o "$RUNNER_TEMP/osv-scanner" \
"https://github.com/google/osv-scanner/releases/download/v${OSV_SCANNER_VERSION}/osv-scanner_linux_amd64"
chmod +x "$RUNNER_TEMP/osv-scanner"
"$RUNNER_TEMP/osv-scanner" scan source --recursive --allow-no-lockfiles --format table .
shell:
name: shell
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install shellcheck
run: |
set -euo pipefail
curl -fsSL -o "$RUNNER_TEMP/shellcheck.tar.xz" \
"https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/shellcheck-v${SHELLCHECK_VERSION}.linux.x86_64.tar.xz"
tar -xJf "$RUNNER_TEMP/shellcheck.tar.xz" -C "$RUNNER_TEMP"
- name: Collect the shell scripts
run: |
set -euo pipefail
# PKGBUILD files are bash without a shebang, so shellcheck would report
# SC2148 on every one of them: makepkg sources them, the gate does not.
git ls-files -z '*.sh' '*.bash' > "$RUNNER_TEMP/scripts"
printf '%s shell files to check\n' "$(tr -cd '\0' < "$RUNNER_TEMP/scripts" | wc -c)"
# SC2086/SC2046 and friends are the shapes an injection takes in shell.
# They stay advisory for now: existing scripts would turn the gate red on
# their first run, so warnings are reported and errors block. SC2148 (no
# shebang) and SC2068 (array quoting, inherited from vendored shell
# integrations) are not signals this gate can act on.
- name: Shellcheck warnings (advisory)
continue-on-error: true
run: |
set -o pipefail
[ -s "$RUNNER_TEMP/scripts" ] || { echo "No shell scripts in this repository."; exit 0; }
xargs -0 -a "$RUNNER_TEMP/scripts" -r \
"$RUNNER_TEMP/shellcheck-v${SHELLCHECK_VERSION}/shellcheck" -x --format=gcc --severity=warning \
--exclude=SC2148,SC2068
- name: Shellcheck errors
run: |
set -euo pipefail
[ -s "$RUNNER_TEMP/scripts" ] || { echo "No shell scripts in this repository."; exit 0; }
xargs -0 -a "$RUNNER_TEMP/scripts" -r \
"$RUNNER_TEMP/shellcheck-v${SHELLCHECK_VERSION}/shellcheck" -x --severity=error \
--exclude=SC2148,SC2068
sast:
name: sast
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- name: Install opengrep
run: |
set -euo pipefail
curl -fsSL -o "$RUNNER_TEMP/opengrep" \
"https://github.com/opengrep/opengrep/releases/download/v${OPENGREP_VERSION}/opengrep_linux_x86"
chmod +x "$RUNNER_TEMP/opengrep"
# Advisory on purpose: the rules flag real injection shapes (SQL, command,
# template, XSS) but also patterns that a codebase already reviewed. Run
# it blocking once the reported findings have been triaged and the false
# positives allowlisted in .semgrepignore.
- name: Injection and unsafe-pattern scan (advisory)
continue-on-error: true
run: |
set -uo pipefail
args=()
git ls-files '*.php' | grep -q . && args+=(--config p/php) || true
git ls-files '*.js' '*.mjs' '*.cjs' '*.ts' | grep -q . && args+=(--config p/javascript) || true
git ls-files '*.py' | grep -q . && args+=(--config p/python) || true
git ls-files '*.go' | grep -q . && args+=(--config p/golang) || true
if [ "${#args[@]}" -eq 0 ]; then
echo "No supported source files in this repository."
exit 0
fi
"$RUNNER_TEMP/opengrep" scan "${args[@]}" --severity ERROR \
--exclude 3rdparty --exclude node_modules --exclude vendor --exclude external .
+18
View File
@@ -0,0 +1,18 @@
# gitleaks flags the empty placeholders of the environment template and a fake
# numeric identifier used by the configuration tests. Everything else keeps the
# default rule set.
[extend]
useDefault = true
[[allowlists]]
description = "Environment template: empty placeholders, not credentials"
paths = [
'''(^|/)\.env\.(example|sample|template)$''',
]
[[allowlists]]
description = "Placeholder identifier from the configuration tests"
regexTarget = "match"
regexes = [
'''123456789012345678''',
]
+17 -11
View File
@@ -129,9 +129,8 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
| | Later saves edit that same message |
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
| `CHANNEL_LOGS_ID` | Functional logs |
| `CHANNEL_LOGS_ID` | Functional and technical logs, ticket journal |
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
| `CHANNEL_TICKETS_LOGS_ID` | Ticket opening/closing journal |
| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications |
| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications |
@@ -143,14 +142,17 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
### Gitea
| Variable | Default | Description |
| ------------------- | ------- | ---------------------------------------------------------------------- |
| `GITEA_URL` | — | Instance URL (without a trailing `/`) |
| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged |
| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) |
| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Request timeout |
| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) |
| Variable | Default | Description |
| ------------------------- | ------------- | ---------------------------------------------------------------------------------- |
| `GITEA_URL` | — | Instance URL (without a trailing `/`) |
| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged |
| `GITEA_RECRUITMENT_TOKEN` | `GITEA_TOKEN` | Admin token (`write:admin`, `write:organization`, `read:user`) used by recruitment |
| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) |
| `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people |
| `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance |
| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Request timeout |
| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) |
### Gitea webhooks
@@ -237,12 +239,16 @@ Resolved from the roles configured in `.env` (highest to lowest):
Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint).
`/ticket setup` publishes a panel with an **Open a ticket** button in the current channel: the member presses the button, picks a category in a menu, and the private channel opens. The panel channel is stored (`ticket_panels`), so the panel survives a restart and a reinstall replaces the previous message instead of stacking a second one.
| Command | Options | Access | State | Description |
| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ |
| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button |
| `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) |
| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel |
| `/ticket setup` | — | **Staff** | ✅ | Publishes and pins the opening panel in this channel (replaces the previous one) |
| `/ticket setup-remove` | — | **Staff** | ✅ | Removes the panel from this channel |
Available categories and who can use them:
@@ -430,7 +436,7 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui
- 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`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run).
- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `ticket_panels` (channel and message of the `/ticket setup` panel), `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`).
+11 -3
View File
@@ -130,15 +130,15 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| `CHANNEL_WELCOME_ID` | Messages de bienvenue |
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
| `CHANNEL_LOGS_ID` | Logs fonctionnels |
| `CHANNEL_LOGS_ID` | Logs fonctionnels et techniques, journal des tickets |
| `CHANNEL_MOD_LOGS_ID` | Logs de modération |
| `CHANNEL_TICKETS_LOGS_ID` | Journal d'ouverture/fermeture des tickets |
| `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests |
| `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits |
| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases |
| `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents |
| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés |
| `CHANNEL_GITEA_APPLICATIONS_ID` | Candidatures Gitea : repli sur `CHANNEL_LOGS_ID` |
| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) |
| `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) |
@@ -148,7 +148,10 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| --- | --- | --- |
| `GITEA_URL` | — | URL de l'instance (sans `/` final) |
| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé |
| `GITEA_RECRUITMENT_TOKEN` | `GITEA_TOKEN` | Jeton admin (`write:admin`, `write:organization`, `read:user`) réservé au recrutement |
| `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) |
| `GITEA_ORG` | `GITEA_OWNER` | Organisation qui accueille les personnes recrutées |
| `GITEA_DEV_TEAM` | `Dev` | Équipe Gitea où elles sont ajoutées à l'acceptation |
| `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes |
| `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) |
@@ -231,6 +234,7 @@ Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) :
| `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) |
| `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes |
| `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) |
| `/gitea panel` | — (modale) | **Staff** | ✅ | Publie ou modifie le panneau de recrutement Gitea |
> Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute.
@@ -238,12 +242,16 @@ Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) :
Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL).
`/ticket setup` publie dans le salon courant un panneau avec un bouton **Ouvrir un ticket** : le membre presse le bouton, choisit sa catégorie dans un menu, et le salon privé s'ouvre. Le salon du panneau est retenu en base (`ticket_panels`), donc le panneau survit au redémarrage et une réinstallation remplace l'ancien message au lieu de l'empiler.
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** |
| `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) |
| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé |
| `/ticket setup` | — | **Staff** | ✅ | Publie et épingle le panneau d'ouverture dans ce salon (remplace le précédent) |
| `/ticket setup-remove` | — | **Staff** | ✅ | Retire le panneau de ce salon |
Catégories disponibles et qui y a accès :
@@ -431,7 +439,7 @@ Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en
- 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`, `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).
- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `ticket_panels` (salon et message du panneau `/ticket setup`), `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`).
+13 -2
View File
@@ -2,15 +2,21 @@ import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { openPanelEditor } from '../../services/gitea/team-recruitment.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { panel: ACCESS_LEVELS.STAFF };
export const data = new SlashCommandBuilder()
.setName('gitea')
.setDescription('Activité Gitea de FWS Arch')
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'))
.addSubcommand((sub) =>
sub.setName('panel').setDescription('Publier ou modifier le panneau de recrutement Gitea'),
);
const commitLines = (commits) =>
bullets(
@@ -22,8 +28,13 @@ const commitLines = (commits) =>
}),
);
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
/** Read-only summaries of the repository (M5-T06 / M5-T07), plus the panel editor. */
export async function execute(interaction) {
if (interaction.options.getSubcommand() === 'panel') {
await openPanelEditor(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
+18 -1
View File
@@ -5,12 +5,19 @@ import {
claimTicket,
closeTicket,
createTicket,
removePanel,
setupPanel,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service.
export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF };
export const subcommandAccess = {
claim: ACCESS_LEVELS.STAFF,
add: ACCESS_LEVELS.STAFF,
setup: ACCESS_LEVELS.STAFF,
'setup-remove': ACCESS_LEVELS.STAFF,
};
export const data = new SlashCommandBuilder()
.setName('ticket')
@@ -33,6 +40,10 @@ export const data = new SlashCommandBuilder()
.setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)),
)
.addSubcommand((sub) =>
sub.setName('setup').setDescription('Publier le panneau d’ouverture de ticket dans ce salon'),
)
.addSubcommand((sub) => sub.setName('setup-remove').setDescription('Retirer le panneau de ce salon'))
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) =>
sub
@@ -60,6 +71,12 @@ export async function execute(interaction) {
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'setup':
await setupPanel(interaction);
return;
case 'setup-remove':
await removePanel(interaction);
return;
case 'claim':
await claimTicket(interaction);
return;
+30 -5
View File
@@ -52,11 +52,36 @@ export const MODERATION_ACTIONS = Object.freeze({
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] },
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] },
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] },
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] },
{ id: 'internal', label: 'Demande interne', scope: ['owner'] },
{
id: 'support',
label: 'Aide et support',
description: 'Une question, besoin d’un coup de main',
scope: ['staff', 'owner'],
},
{
id: 'bug',
label: 'Bug',
description: 'Quelque chose ne marche pas comme prévu',
scope: ['staff', 'dev', 'owner'],
},
{
id: 'dev-question',
label: 'Question de développement',
description: 'Conseil, architecture, code',
scope: ['dev', 'owner'],
},
{
id: 'report',
label: 'Signalement',
description: 'Un membre ou un message pose problème',
scope: ['staff', 'owner'],
},
{
id: 'internal',
label: 'Demande interne',
description: 'Réservé à l’équipe',
scope: ['owner'],
},
]);
/** Gitea webhook event -> notification type (M9-T03). */
+6 -1
View File
@@ -43,13 +43,13 @@ export const env = Object.freeze({
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
logs: read('CHANNEL_LOGS_ID'),
modLogs: read('CHANNEL_MOD_LOGS_ID'),
ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'),
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
ticketCategory: read('CATEGORY_TICKETS_ID'),
giteaApplications: read('CHANNEL_GITEA_APPLICATIONS_ID'),
voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'),
voiceCategory: read('CATEGORY_VOICE_ID'),
},
@@ -65,8 +65,13 @@ export const env = Object.freeze({
gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'),
// Admin calls need `write:admin`: recruitment has its own token so the
// everyday one can stay least privileged.
recruitToken: read('GITEA_RECRUITMENT_TOKEN') || read('GITEA_TOKEN'),
owner: read('GITEA_OWNER'),
repo: read('GITEA_REPO'),
org: read('GITEA_ORG') || read('GITEA_OWNER'),
devTeam: read('GITEA_DEV_TEAM', 'Dev'),
timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000),
maxRetries: readInt('GITEA_MAX_RETRIES', 2),
},
+18
View File
@@ -23,6 +23,11 @@ export const SETTING_SECTIONS = Object.freeze([
summary: 'Message affiché et épinglé dans le salon des règles.',
},
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{
id: 'recruitment',
title: 'Recrutement Gitea',
summary: 'Le message du salon « rejoindre l’équipe » et les candidatures.',
},
{
id: 'voice',
title: 'Salons vocaux',
@@ -136,6 +141,19 @@ export const GUILD_SETTINGS = Object.freeze([
default: true,
},
// --- Recrutement Gitea -----------------------------------------------------
{
key: 'gitea.recruitmentText',
section: 'recruitment',
label: 'Texte du panneau de recrutement',
help: 'Description de l’embed publié dans le salon « rejoindre l’équipe ». `/gitea panel` la modifie et republie le panneau.',
type: 'markdown',
default:
'Tu veux contribuer sur Gitea ? Postule pour rejoindre l’équipe : on cherche des personnes motivées, quel que soit le niveau.\n\n' +
'Remplis le formulaire avec le bouton ci-dessous. On lit chaque candidature et on te répond en message privé.',
maxLength: 4000,
},
// --- Salons vocaux ---------------------------------------------------------
{
key: 'voice.adoptOrphans',
@@ -0,0 +1,13 @@
-- The ticket panel published by `/ticket setup`
--
-- The panel is a button that opens a ticket, and it has to survive a restart:
-- the channel alone is not enough, because reinstalling must replace the previous
-- message instead of leaving an outdated copy in the salon.
CREATE TABLE IF NOT EXISTS ticket_panels (
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
message_id TEXT NOT NULL,
created_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (guild_id, channel_id)
);
@@ -0,0 +1,40 @@
-- Gitea team recruitment (M20)
--
-- Applications are stored before the team reviews them: the panel is pressed by
-- members, not staff, so losing an application on restart would mean asking
-- someone to fill the whole form again. The panel message is remembered too, so
-- re-running the installation edits it instead of stacking a second copy.
CREATE TABLE IF NOT EXISTS gitea_applications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
user_id TEXT NOT NULL,
languages TEXT NOT NULL,
level TEXT NOT NULL,
experience TEXT,
gitea_username TEXT NOT NULL,
email TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'rejected')),
channel_id TEXT,
message_id TEXT,
reviewed_by TEXT,
reviewed_at TEXT,
gitea_user_id INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- One open application per member: a second one would give the team two
-- buttons for the same person and could create their Gitea account twice.
CREATE UNIQUE INDEX IF NOT EXISTS idx_gitea_applications_pending_member
ON gitea_applications (guild_id, user_id) WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_gitea_applications_status
ON gitea_applications (guild_id, status);
CREATE TABLE IF NOT EXISTS gitea_recruitment_panels (
guild_id TEXT PRIMARY KEY,
category_id TEXT,
channel_id TEXT NOT NULL,
message_id TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@@ -0,0 +1,6 @@
-- Reason shown to the applicant when the team refuses an application.
--
-- A refusal without a reason reads as a rejection of the person; the team writes
-- one sentence and the bot forwards it verbatim in the DM.
ALTER TABLE gitea_applications ADD COLUMN rejection_reason TEXT;
@@ -0,0 +1,129 @@
import { getDatabase } from '../index.js';
// --- Applications -----------------------------------------------------------
export function createApplication({
guildId,
userId,
languages,
level,
experience = null,
giteaUsername,
email,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO gitea_applications
(guild_id, user_id, languages, level, experience, gitea_username, email)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
)
.run(guildId, userId, languages, level, experience, giteaUsername, email);
return Number(lastInsertRowid);
}
export function getApplication(id) {
return getDatabase().prepare('SELECT * FROM gitea_applications WHERE id = ?').get(id) ?? null;
}
export function getPendingApplicationByMember({ guildId, userId }) {
return (
getDatabase()
.prepare(
`SELECT * FROM gitea_applications
WHERE guild_id = ? AND user_id = ? AND status = 'pending'`,
)
.get(guildId, userId) ?? null
);
}
/** Gitea compares usernames without case, so the pending check must too. */
export function getPendingApplicationByUsername({ guildId, username }) {
return (
getDatabase()
.prepare(
`SELECT * FROM gitea_applications
WHERE guild_id = ? AND status = 'pending' AND lower(gitea_username) = lower(?)`,
)
.get(guildId, username) ?? null
);
}
export function listPendingApplications({ guildId, limit = 25 }) {
return getDatabase()
.prepare(
`SELECT * FROM gitea_applications
WHERE guild_id = ? AND status = 'pending'
ORDER BY id ASC LIMIT ?`,
)
.all(guildId, limit);
}
/**
* Reserves an application before the Gitea call: the conditional update makes
* the second click on « Accepter » lose the race instead of creating a second
* account.
*/
export function claimApplication(id, reviewerId) {
return getDatabase()
.prepare(
`UPDATE gitea_applications
SET status = 'accepted', reviewed_by = ?, reviewed_at = datetime('now')
WHERE id = ? AND status = 'pending'`,
)
.run(reviewerId, id).changes;
}
/** Puts a claimed application back in the queue after a failed Gitea call. */
export function releaseApplication(id) {
return getDatabase()
.prepare(
`UPDATE gitea_applications
SET status = 'pending', reviewed_by = NULL, reviewed_at = NULL, gitea_user_id = NULL
WHERE id = ? AND status = 'accepted'`,
)
.run(id).changes;
}
export function rejectApplication(id, reviewerId, reason = null) {
return getDatabase()
.prepare(
`UPDATE gitea_applications
SET status = 'rejected', reviewed_by = ?, reviewed_at = datetime('now'), rejection_reason = ?
WHERE id = ? AND status = 'pending'`,
)
.run(reviewerId, reason, id).changes;
}
export function setApplicationGiteaUser(id, giteaUserId) {
return getDatabase()
.prepare('UPDATE gitea_applications SET gitea_user_id = ? WHERE id = ?')
.run(giteaUserId ?? null, id).changes;
}
export function setApplicationMessage(id, { channelId, messageId }) {
return getDatabase()
.prepare('UPDATE gitea_applications SET channel_id = ?, message_id = ? WHERE id = ?')
.run(channelId, messageId, id).changes;
}
// --- Recruitment panel ------------------------------------------------------
export function getRecruitmentPanel(guildId) {
return (
getDatabase().prepare('SELECT * FROM gitea_recruitment_panels WHERE guild_id = ?').get(guildId) ?? null
);
}
export function setRecruitmentPanel({ guildId, categoryId, channelId, messageId }) {
getDatabase()
.prepare(
`INSERT INTO gitea_recruitment_panels (guild_id, category_id, channel_id, message_id)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id) DO UPDATE SET
category_id = excluded.category_id,
channel_id = excluded.channel_id,
message_id = excluded.message_id,
updated_at = datetime('now')`,
)
.run(guildId, categoryId ?? null, channelId, messageId ?? null);
}
@@ -69,3 +69,38 @@ export function countOpenTickets(guildId) {
.get(guildId);
return row.count;
}
// --- Ticket panels (`/ticket setup`) ----------------------------------------
export function setTicketPanel({ guildId, channelId, messageId, createdBy = null }) {
getDatabase()
.prepare(
`INSERT INTO ticket_panels (guild_id, channel_id, message_id, created_by)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, channel_id) DO UPDATE SET
message_id = excluded.message_id,
created_by = excluded.created_by,
updated_at = datetime('now')`,
)
.run(guildId, channelId, messageId, createdBy);
}
export function getTicketPanel({ guildId, channelId }) {
return (
getDatabase()
.prepare('SELECT * FROM ticket_panels WHERE guild_id = ? AND channel_id = ?')
.get(guildId, channelId) ?? null
);
}
export function listTicketPanels({ guildId }) {
return getDatabase()
.prepare('SELECT * FROM ticket_panels WHERE guild_id = ? ORDER BY updated_at DESC')
.all(guildId);
}
export function deleteTicketPanel({ guildId, channelId }) {
return getDatabase()
.prepare('DELETE FROM ticket_panels WHERE guild_id = ? AND channel_id = ?')
.run(guildId, channelId).changes;
}
+6
View File
@@ -1,5 +1,6 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { installRecruitmentPanel } from '../services/gitea/team-recruitment.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import {
@@ -23,6 +24,11 @@ export async function execute(client) {
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
// The Gitea recruitment salon is created on the first start and repaired on
// every later one; a permission problem must not keep the bot offline.
await installRecruitmentPanel(client).catch((error) =>
log.warn('Could not install the Gitea recruitment panel', error),
);
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
+2
View File
@@ -4,6 +4,7 @@ import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js';
import { handleGiteaModal } from '../services/gitea/gitea-modals.js';
import { handleTeamComponent, handleTeamModal } from '../services/gitea/team-recruitment.js';
import { handlePollComponent } from '../services/polls/poll-service.js';
import { handleTicketComponent } from '../services/tickets/ticket-service.js';
import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js';
@@ -20,6 +21,7 @@ const routes = [
{ prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal },
{ prefix: 'issue:', modal: handleGiteaModal },
{ prefix: 'pr:', modal: handleGiteaModal },
{ prefix: 'gitea-team:', component: handleTeamComponent, modal: handleTeamModal },
];
async function replyError(interaction, message) {
+64 -3
View File
@@ -4,9 +4,12 @@ import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Administration calls need `write:admin`, which recruitment keeps on its own token. */
const recruitmentToken = () => env.gitea.recruitToken || env.gitea.token;
/** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) {
export async function giteaRequest(endpoint, { method = 'GET', body, token = env.gitea.token } = {}) {
if (!env.gitea.url || !token) {
throw new ExternalApiError('gitea', 'Gitea is not configured');
}
@@ -15,7 +18,7 @@ export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method,
headers: {
Authorization: `token ${env.gitea.token}`,
Authorization: `token ${token}`,
Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }),
},
@@ -39,6 +42,11 @@ export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token);
}
/** True when the recruitment token (or its fallback) is available. */
export function isGiteaRecruitmentConfigured() {
return Boolean(env.gitea.url && recruitmentToken());
}
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) {
if (Array.isArray(payload)) return payload;
@@ -67,3 +75,56 @@ export const gitea = {
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
};
/**
* Administration calls used by recruitment only: creating an account and
* joining a team require `write:admin` / `write:organization`, which the
* everyday token must not carry.
*/
export const giteaRecruitment = {
getUser: (username) =>
giteaRequest(`/users/${encodeURIComponent(username)}`, { token: recruitmentToken() }),
createUser: ({ username, email, password, mustChangePassword = true }) =>
giteaRequest('/admin/users', {
method: 'POST',
token: recruitmentToken(),
body: {
username,
email,
password,
must_change_password: mustChangePassword,
visibility: 'public',
// Recruited accounts must not browse the whole forge: with `restricted`
// Gitea only shows them the repositories their teams give access to.
restricted: true,
},
}),
deleteUser: (username) =>
giteaRequest(`/admin/users/${encodeURIComponent(username)}?purge=true`, {
method: 'DELETE',
token: recruitmentToken(),
}),
updateUser: (username, body) =>
giteaRequest(`/admin/users/${encodeURIComponent(username)}`, {
method: 'PATCH',
body,
token: recruitmentToken(),
}),
listTeams: (org) =>
giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`, { token: recruitmentToken() }),
addTeamMember: (teamId, username) =>
giteaRequest(`/teams/${teamId}/members/${encodeURIComponent(username)}`, {
method: 'PUT',
token: recruitmentToken(),
}),
};
/** Returns the Gitea user, or null when the name is still free. */
export async function findGiteaUser(username) {
try {
return await giteaRecruitment.getUser(username);
} catch (error) {
if (error.status === 404) return null;
throw error;
}
}
+800
View File
@@ -0,0 +1,800 @@
import { randomInt } from 'node:crypto';
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
MessageFlags,
ModalBuilder,
TextInputBuilder,
TextInputStyle,
} from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { readSetting, writeSetting } from '../../config/guild-settings.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { hasAccess } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
claimApplication,
createApplication,
getApplication,
getPendingApplicationByMember,
getPendingApplicationByUsername,
getRecruitmentPanel,
releaseApplication,
rejectApplication,
setApplicationGiteaUser,
setApplicationMessage,
setRecruitmentPanel,
} from '../../database/repositories/gitea-recruitment-repository.js';
import { baseEmbed, bullets, errorEmbed, successEmbed, warningEmbed } from '../../ui/embeds.js';
import { asList, findGiteaUser, giteaRecruitment, isGiteaRecruitmentConfigured } from './gitea-client.js';
import { replyGiteaFailure } from './gitea-modals.js';
/**
* Gitea team recruitment (M20).
*
* The panel lives in a category of its own. The button opens one modal with the
* five questions, in two blocks: the member, then the Gitea account. Discord
* forbids answering a modal with another modal, so a single form is the only
* way to keep the whole application in one gesture.
*/
const log = createLogger('gitea-recruitment');
export const CATEGORY_NAME = '════ GITEA ════';
// Discord strips apostrophes from channel names, so the dash keeps the words apart.
export const CHANNEL_NAME = 'rejoindre-l-équipe';
export const RECRUITMENT_SETTING = 'gitea.recruitmentText';
const USERNAME_MAX = 39;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const USERNAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9-_.]{0,38}$/;
/** Ambiguous characters are left out: the password is read from a DM and typed. */
const PASSWORD_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%*-_';
export function generatePassword(length = 20) {
let password = '';
for (let index = 0; index < length; index += 1) {
password += PASSWORD_ALPHABET[randomInt(PASSWORD_ALPHABET.length)];
}
return password;
}
/** Returns null when the name is usable, a French explanation otherwise. */
export function validateGiteaUsername(value) {
const username = String(value ?? '').trim();
if (username === '') return 'Indique le nom d’utilisateur Gitea que tu veux.';
if (username.length > USERNAME_MAX) return `${USERNAME_MAX} caractères maximum pour un nom Gitea.`;
if (!USERNAME_PATTERN.test(username)) {
return 'Un nom Gitea commence par une lettre ou un chiffre, puis des lettres, chiffres, points, tirets ou underscores.';
}
return null;
}
export function validateEmail(value) {
const email = String(value ?? '').trim();
if (email === '') return 'Indique une adresse e-mail : elle sert à créer ton compte Gitea.';
if (email.length > 254) return 'Cette adresse e-mail est trop longue.';
if (!EMAIL_PATTERN.test(email)) return 'Cette adresse e-mail ne ressemble pas à une adresse valide.';
return null;
}
// --- Panel ------------------------------------------------------------------
const panelEmbed = (text) =>
baseEmbed(COLORS.gitea)
.setTitle('🤝 Rejoindre l’équipe Gitea')
.setDescription(text)
.addFields({
name: 'Comment ça se passe',
value: bullets([
'tu réponds à quelques questions, puis tu choisis ton compte Gitea',
'l’équipe lit la candidature et accepte ou refuse',
'si c’est accepté, ton mot de passe provisoire arrive en message privé',
]),
});
function panelComponents() {
return [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('gitea-team:apply')
.setLabel('Rejoindre l’équipe')
.setEmoji('🤝')
.setStyle(ButtonStyle.Primary),
),
];
}
async function resolveCategory(guild, storedId) {
if (storedId) {
const stored = await guild.channels.fetch(storedId).catch(() => null);
if (stored?.type === ChannelType.GuildCategory) return stored;
}
const existing = guild.channels.cache.find(
(channel) => channel.type === ChannelType.GuildCategory && channel.name === CATEGORY_NAME,
);
if (existing) return existing;
return guild.channels.create({
name: CATEGORY_NAME,
type: ChannelType.GuildCategory,
reason: 'Espace Gitea créé par FWS-Bot',
});
}
async function resolveChannel(guild, category, storedId) {
if (storedId) {
const stored = await guild.channels.fetch(storedId).catch(() => null);
if (stored?.type === ChannelType.GuildText) {
// An older name or a moved salon is repaired here rather than duplicated.
if (stored.name !== CHANNEL_NAME) {
await stored
.setName(CHANNEL_NAME)
.catch((error) => log.debug('Could not rename the recruitment salon', error));
}
if (stored.parentId !== category.id) {
await stored
.setParent(category.id)
.catch((error) => log.debug('Could not move the recruitment salon', error));
}
return stored;
}
}
const existing =
category.children?.cache?.find(
(channel) => channel.type === ChannelType.GuildText && channel.name === CHANNEL_NAME,
) ??
guild.channels.cache.find(
(channel) => channel.type === ChannelType.GuildText && channel.name === CHANNEL_NAME,
);
if (existing && existing.parentId === category.id) return existing;
return guild.channels.create({
name: CHANNEL_NAME,
type: ChannelType.GuildText,
parent: category.id,
topic: 'Candidatures pour rejoindre l’équipe Gitea',
reason: 'Salon de recrutement Gitea créé par FWS-Bot',
});
}
/**
* Creates the category, the salon and the panel when they are missing, and
* edits the existing message otherwise. Safe to call on every start.
*/
export async function ensureRecruitmentPanel(client, { guildId = env.discord.guildId, text } = {}) {
if (!guildId) throw new UserFacingError('Aucun serveur Discord n’est configuré (`DISCORD_GUILD_ID`).');
const guild = await client.guilds.fetch(guildId).catch(() => null);
if (!guild) {
throw new UserFacingError(
'Je ne trouve pas ce serveur Discord : vérifie que le bot y est invité et que `DISCORD_GUILD_ID` est correct.',
);
}
const stored = getRecruitmentPanel(guildId);
const category = await resolveCategory(guild, stored?.category_id);
const channel = await resolveChannel(guild, category, stored?.channel_id);
const content = String(text ?? readSetting(RECRUITMENT_SETTING, guildId)).trim();
const embed = panelEmbed(content);
let message = null;
let edited = false;
if (stored?.message_id && stored.channel_id === channel.id) {
const previous = await channel.messages?.fetch(stored.message_id).catch(() => null);
if (previous) {
message = await previous
.edit({ embeds: [embed], components: panelComponents() })
.then((result) => result ?? previous)
.catch((error) => {
log.warn('Could not edit the recruitment panel', error);
return null;
});
edited = Boolean(message);
}
}
if (!message) {
message = await channel.send({ embeds: [embed], components: panelComponents() });
// A bot without “Gérer les messages” still installs the panel.
await message.pin().catch((error) => log.debug('Could not pin the recruitment panel', error));
}
setRecruitmentPanel({
guildId,
categoryId: category.id,
channelId: channel.id,
messageId: message.id,
});
return { guildId, categoryId: category.id, channelId: channel.id, messageId: message.id, edited };
}
/** Called at startup: a failure here must never keep the bot offline. */
export async function installRecruitmentPanel(client) {
const panel = await ensureRecruitmentPanel(client);
log.info('Gitea recruitment panel ready', panel);
return panel;
}
/** `/gitea panel`: edits the embed text and republishes it in the salon. */
export async function openPanelEditor(interaction) {
const text = readSetting(RECRUITMENT_SETTING, interaction.guildId ?? env.discord.guildId);
await interaction.showModal(
new ModalBuilder()
.setCustomId('gitea-team:panel')
.setTitle('Panneau de recrutement Gitea')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('text')
.setLabel('Texte de présentation')
.setStyle(TextInputStyle.Paragraph)
.setMaxLength(4000)
.setRequired(true)
.setValue(text),
),
),
);
}
async function submitPanelEditor(interaction) {
const guildId = interaction.guildId ?? env.discord.guildId;
const text = interaction.fields.getTextInputValue('text').trim();
if (text === '') throw new UserFacingError('Le panneau ne peut pas être vide.');
writeSetting(RECRUITMENT_SETTING, text, { guildId, updatedBy: interaction.user.id });
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const panel = await ensureRecruitmentPanel(interaction.client, { guildId, text });
logEvent({
guildId,
type: 'gitea.recruitment.panel',
actorId: interaction.user.id,
payload: panel,
});
await interaction.editReply({
embeds: [
successEmbed(`Panneau publié dans <#${panel.channelId}>. Les membres peuvent postuler avec le bouton.`),
],
});
}
// --- Application -------------------------------------------------------------
function modal(customId, title, fields) {
return new ModalBuilder()
.setCustomId(customId)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true)
.setPlaceholder(field.placeholder ?? ''),
),
),
);
}
function applicationEmbed(application, { reviewedBy = null } = {}) {
const statusLabel = {
pending: 'En attente',
accepted: 'Acceptée',
rejected: 'Refusée',
}[application.status];
const embed = baseEmbed(application.status === 'rejected' ? COLORS.error : COLORS.gitea)
.setTitle(`📨 Candidature Gitea #${application.id}`)
.addFields(
{ name: 'Membre', value: `<@${application.user_id}>` },
{ name: 'Langages', value: String(application.languages).slice(0, 1000) },
{ name: 'Niveau', value: String(application.level).slice(0, 1000) },
{ name: 'Motivation', value: String(application.experience || 'Non précisée').slice(0, 1000) },
{ name: 'Compte Gitea', value: `\`${application.gitea_username}\``, inline: true },
{ name: 'E-mail', value: `\`${application.email}\``, inline: true },
{ name: 'Statut', value: statusLabel, inline: true },
);
if (application.rejection_reason) {
embed.addFields({ name: 'Raison du refus', value: String(application.rejection_reason).slice(0, 1000) });
}
if (reviewedBy) embed.addFields({ name: 'Traitée par', value: `<@${reviewedBy}>` });
return embed;
}
function applicationComponents(application) {
if (application.status !== 'pending') return [];
return [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId(`gitea-team:accept:${application.id}`)
.setLabel('Accepter')
.setEmoji('✅')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`gitea-team:reject:${application.id}`)
.setLabel('Refuser')
.setEmoji('✖️')
.setStyle(ButtonStyle.Danger),
),
];
}
/** Where verdicts are posted: its own salon, or the technical logs. */
async function resolveReviewChannel(client) {
const channelId = env.channels.giteaApplications || env.channels.logs;
if (!channelId) {
throw new UserFacingError(
'Les candidatures n’ont pas de salon : renseigne `CHANNEL_GITEA_APPLICATIONS_ID` (ou `CHANNEL_LOGS_ID`) dans le `.env`.',
);
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
throw new UserFacingError(
'Le salon des candidatures est introuvable, ou je n’ai pas le droit d’y écrire. L’équipe doit vérifier `CHANNEL_GITEA_APPLICATIONS_ID`.',
);
}
return channel;
}
export async function openApplicationModal(interaction) {
await interaction.showModal(
modal('gitea-team:form', 'Candidature — toi et ton compte Gitea', [
{
id: 'languages',
label: 'Langages de programmation',
maxLength: 200,
placeholder: 'Python, JavaScript, Rust…',
},
{
id: 'level',
label: 'Ton niveau',
maxLength: 100,
placeholder: 'Débutant, intermédiaire, avancé…',
},
{
id: 'experience',
label: 'Ce que tu veux apporter',
paragraph: true,
maxLength: 500,
required: false,
placeholder: 'Projets, disponibilité, expérience…',
},
{
id: 'username',
label: 'Pseudo Gitea souhaité',
maxLength: USERNAME_MAX,
placeholder: 'ton-pseudo',
},
{ id: 'email', label: 'Adresse e-mail', maxLength: 254, placeholder: 'toi@exemple.org' },
]),
);
}
async function submitApplication(interaction) {
const context = {
languages: interaction.fields.getTextInputValue('languages').trim(),
level: interaction.fields.getTextInputValue('level').trim(),
experience: interaction.fields.getTextInputValue('experience').trim() || null,
};
const username = interaction.fields.getTextInputValue('username').trim();
const email = interaction.fields.getTextInputValue('email').trim();
const usernameError = validateGiteaUsername(username);
if (usernameError) throw new UserFacingError(usernameError);
const emailError = validateEmail(email);
if (emailError) throw new UserFacingError(emailError);
if (!isGiteaRecruitmentConfigured()) {
throw new UserFacingError(
'Le recrutement Gitea n’est pas encore configuré : l’équipe doit renseigner `GITEA_URL` et `GITEA_RECRUITMENT_TOKEN`. Réessaie plus tard.',
);
}
const guildId = interaction.guildId ?? env.discord.guildId;
const channel = await resolveReviewChannel(interaction.client);
if (getPendingApplicationByMember({ guildId, userId: interaction.user.id })) {
throw new UserFacingError(
'Tu as déjà une candidature en attente : l’équipe la lit en ce moment. Tu recevras la réponse en message privé.',
);
}
if (getPendingApplicationByUsername({ guildId, username })) {
throw new UserFacingError(
'Ce nom d’utilisateur Gitea est déjà demandé par une autre candidature en attente. Choisis-en un autre.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
let existing;
try {
existing = await findGiteaUser(username);
} catch (error) {
await replyGiteaFailure(interaction, error);
return;
}
if (existing) {
throw new UserFacingError(
`Le nom **${username}** est déjà pris sur Gitea. Reclique sur **Rejoindre l’équipe** et choisis-en un autre.`,
);
}
const id = createApplication({
guildId,
userId: interaction.user.id,
languages: context.languages,
level: context.level,
experience: context.experience,
giteaUsername: username,
email,
});
const application = getApplication(id);
const message = await channel.send({
embeds: [applicationEmbed(application)],
components: applicationComponents(application),
});
setApplicationMessage(id, { channelId: channel.id, messageId: message.id });
logEvent({
guildId,
type: 'gitea.recruitment.applied',
actorId: interaction.user.id,
payload: { id, username },
});
await interaction.editReply({
embeds: [
successEmbed(
`Ta candidature est partie : <#${channel.id}>. L’équipe la lit et te répond en message privé — garde tes MP ouverts.`,
),
],
});
}
// --- Review ------------------------------------------------------------------
/**
* Removes what a recruited account could do outside the organization: no
* personal repositories, no organization of its own. The team still allows
* creating repositories inside FWS.
*/
export async function lockGiteaAccount(username) {
try {
await giteaRecruitment.updateUser(username, {
restricted: true,
max_repo_creation: 0,
allow_create_organization: false,
});
return { locked: true };
} catch (error) {
log.error('Could not lock the new Gitea account', error);
return { locked: false, reason: 'Gitea a refusé les restrictions' };
}
}
/**
* Puts the new account in the organization's developer team. Recruited people
* have no other organization, so this team is the only place they can work.
*/
export async function addToDeveloperTeam(username) {
const org = env.gitea.org;
const teamName = env.gitea.devTeam;
if (!org || !teamName) return { added: false, reason: 'organisation ou équipe non configurée' };
const teams = asList(await giteaRecruitment.listTeams(org));
const team = teams.find((entry) => String(entry.name).toLowerCase() === teamName.toLowerCase());
if (!team) return { added: false, reason: `équipe « ${teamName} » introuvable dans ${org}` };
await giteaRecruitment.addTeamMember(team.id, username);
return { added: true, team: team.name };
}
/** Gives the accepted member the Discord Dev role, when one is configured. */
async function grantDeveloperRole(interaction, userId) {
if (!env.roles.dev) return { added: false, reason: 'ROLE_DEV_ID non configuré' };
const member = await interaction.guild?.members?.fetch(userId).catch(() => null);
if (!member) return { added: false, reason: 'membre introuvable sur le serveur' };
return member.roles
.add(env.roles.dev)
.then(() => ({ added: true }))
.catch((error) => {
log.warn('Could not grant the Dev role', error);
return { added: false, reason: 'permission refusée par Discord' };
});
}
function credentialsEmbed(username, password) {
return baseEmbed(COLORS.gitea)
.setTitle('✅ Ton accès Gitea est prêt')
.setDescription(
`Ta candidature a été acceptée. Voici ton compte :\n\n` +
`**Identifiant** : \`${username}\`\n` +
`**Mot de passe provisoire** : \`${password}\``,
)
.addFields({
name: 'Première connexion',
value: bullets([
`connecte-toi sur ${env.gitea.url}`,
'change ton mot de passe dès la première connexion',
'garde-le pour toi : il ne sera plus affiché ensuite',
]),
});
}
async function acceptApplication(interaction, application) {
if (!isGiteaRecruitmentConfigured()) {
throw new UserFacingError(
'Gitea n’est pas configuré (`GITEA_URL` et `GITEA_RECRUITMENT_TOKEN`) : impossible de créer le compte pour l’instant.',
);
}
if (claimApplication(application.id, interaction.user.id) === 0) {
throw new UserFacingError('Cette candidature vient d’être traitée par quelqu’un d’autre.');
}
await interaction.deferUpdate();
const password = generatePassword();
let created;
try {
created = await giteaRecruitment.createUser({
username: application.gitea_username,
email: application.email,
password,
mustChangePassword: true,
});
} catch (error) {
releaseApplication(application.id);
log.error('Gitea refused a team account creation', error);
let reason = 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.';
if (error.status === 422) {
reason =
'Gitea a refusé : ce nom ou cette adresse e-mail est déjà utilisé. Demande au membre d’en choisir un autre.';
}
if (error.status === 403) {
reason =
'Gitea a refusé l’appel : le jeton de recrutement n’a pas les droits d’administration. ' +
'Il lui faut la portée `write:admin` (`GITEA_RECRUITMENT_TOKEN`).';
}
await interaction.followUp({
embeds: [errorEmbed(reason)],
flags: MessageFlags.Ephemeral,
});
return;
}
setApplicationGiteaUser(application.id, created?.id);
const reviewed = { ...application, status: 'accepted', reviewed_by: interaction.user.id };
const [team, role, lock] = await Promise.all([
addToDeveloperTeam(application.gitea_username).catch((error) => {
log.error('Could not add the new account to the developer team', error);
return { added: false, reason: 'erreur Gitea' };
}),
grantDeveloperRole(interaction, application.user_id),
lockGiteaAccount(application.gitea_username),
]);
const applicant = await interaction.client.users.fetch(application.user_id).catch(() => null);
const delivered = await applicant
?.send({ embeds: [credentialsEmbed(application.gitea_username, password)] })
.then(() => true)
.catch(() => false);
logEvent({
guildId: application.guild_id,
type: 'gitea.recruitment.accepted',
actorId: interaction.user.id,
payload: {
id: application.id,
username: application.gitea_username,
giteaUserId: created?.id ?? null,
delivered,
team: team.added ? team.team : null,
discordRole: role.added,
giteaLocked: lock.locked,
},
});
await interaction.editReply({
embeds: [applicationEmbed(reviewed, { reviewedBy: interaction.user.id })],
components: [],
});
if (!delivered) {
// The account exists: the password must reach the member somehow, and the
// ephemeral reply is the only place that does not expose it to the salon.
await interaction.followUp({
embeds: [
errorEmbed(
`Je n’ai pas pu écrire à <@${application.user_id}> (messages privés fermés). ` +
`Transmets-lui ces identifiants toi-même : identifiant \`${application.gitea_username}\`, mot de passe \`${password}\`.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
const warnings = [];
if (!team.added)
warnings.push(`l’ajout à l’équipe Gitea « ${env.gitea.devTeam} » a échoué (${team.reason})`);
if (!role.added) warnings.push(`le rôle Discord Dev n’a pas été attribué (${role.reason})`);
if (!lock.locked) warnings.push(`le compte Gitea n’a pas pu être verrouillé (${lock.reason})`);
if (warnings.length > 0) {
await interaction.followUp({
embeds: [
warningEmbed(
`${bullets(warnings)}\n\nLe compte Gitea existe déjà : corrige ces deux points à la main, ne recrée pas la candidature.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
}
/**
* A refusal is written, not clicked away: the modal makes the reason mandatory,
* and it is the only thing the member gets to read.
*/
export async function openRejectionModal(interaction, application) {
await interaction.showModal(
modal(`gitea-team:reject:${application.id}`, `Refus de la candidature #${application.id}`, [
{
id: 'reason',
label: 'Pourquoi cette candidature est refusée',
paragraph: true,
maxLength: 500,
placeholder: 'Le membre reçoit ce texte : sois précis et courtois.',
},
]),
);
}
function rejectionEmbed(reason) {
return baseEmbed(COLORS.info)
.setTitle('Ta candidature Gitea')
.setDescription('Merci d’avoir postulé ! L’équipe n’a pas retenu ta candidature cette fois.')
.addFields(
{ name: 'La raison', value: String(reason).slice(0, 1000) },
{
name: 'Et ensuite',
value: 'Tu peux continuer à contribuer sur le serveur et retenter plus tard.',
},
);
}
async function submitRejection(interaction, idText) {
if (!hasAccess(interaction.member, ACCESS_LEVELS.STAFF)) {
throw new PermissionDeniedError('Seule l’équipe peut refuser une candidature.');
}
const application = getApplication(Number.parseInt(idText, 10));
if (!application) throw new UserFacingError('Cette candidature n’existe plus.');
if (application.status !== 'pending') {
throw new UserFacingError(
`Cette candidature est déjà ${application.status === 'accepted' ? 'acceptée' : 'refusée'}.`,
);
}
const reason = interaction.fields.getTextInputValue('reason').trim();
if (reason === '') {
throw new UserFacingError('Indique la raison du refus : elle est envoyée au membre.');
}
if (rejectApplication(application.id, interaction.user.id, reason) === 0) {
throw new UserFacingError('Cette candidature vient d’être traitée par quelqu’un d’autre.');
}
await interaction.deferUpdate();
const applicant = await interaction.client.users.fetch(application.user_id).catch(() => null);
const notified = await applicant
?.send({ embeds: [rejectionEmbed(reason)] })
.then(() => true)
.catch(() => false);
logEvent({
guildId: application.guild_id,
type: 'gitea.recruitment.rejected',
actorId: interaction.user.id,
payload: { id: application.id, notified },
});
await interaction.editReply({
embeds: [
applicationEmbed(
{ ...application, status: 'rejected', rejection_reason: reason },
{ reviewedBy: interaction.user.id },
),
],
components: [],
});
if (!notified) {
// The refusal is still recorded: the team can pass the reason along itself.
await interaction.followUp({
embeds: [
errorEmbed(
`Je n’ai pas pu écrire à <@${application.user_id}> (messages privés fermés). ` +
`Transmets-lui la raison toi-même : « ${reason} »`,
),
],
flags: MessageFlags.Ephemeral,
});
}
}
export async function reviewApplication(interaction, decision, idText) {
if (!hasAccess(interaction.member, ACCESS_LEVELS.STAFF)) {
throw new PermissionDeniedError(
'Seule l’équipe peut accepter ou refuser une candidature. Si tu as postulé, attends la réponse en message privé.',
);
}
const application = getApplication(Number.parseInt(idText, 10));
if (!application) throw new UserFacingError('Cette candidature n’existe plus.');
if (application.status !== 'pending') {
throw new UserFacingError(
`Cette candidature est déjà ${application.status === 'accepted' ? 'acceptée' : 'refusée'}.`,
);
}
if (decision === 'reject') {
await openRejectionModal(interaction, application);
return;
}
await acceptApplication(interaction, application);
}
// --- Routing -----------------------------------------------------------------
export async function handleTeamComponent(interaction) {
if (interaction.customId === 'gitea-team:apply') {
await openApplicationModal(interaction);
return;
}
const match = /^gitea-team:(accept|reject):(\d+)$/.exec(interaction.customId);
if (!match) {
log.debug(`Ignored unknown recruitment component ${interaction.customId}`);
return;
}
await reviewApplication(interaction, match[1], match[2]);
}
export async function handleTeamModal(interaction) {
switch (interaction.customId) {
case 'gitea-team:form':
await submitApplication(interaction);
return;
case 'gitea-team:panel':
await submitPanelEditor(interaction);
return;
default: {
const rejection = /^gitea-team:reject:(\d+)$/.exec(interaction.customId);
if (rejection) {
await submitRejection(interaction, rejection[1]);
return;
}
log.debug(`Ignored unknown recruitment modal ${interaction.customId}`);
}
}
}
+225 -22
View File
@@ -1,4 +1,4 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ChannelType, MessageFlags, 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';
@@ -10,10 +10,13 @@ import {
claimTicket as claimTicketRow,
closeTicket as closeTicketRow,
createTicket as createTicketRow,
deleteTicketPanel,
getTicketByChannel,
getTicketPanel,
setTicketPanel,
} from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
import { ticketButtons, ticketCategorySelect, ticketPanelButton } from '../../ui/buttons.js';
import { TONE, baseEmbed, bullets, errorEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
@@ -39,10 +42,7 @@ function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`🎫 Ticket ${category.label} #${ticket.id}`)
.setDescription(
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
)
.setDescription(`<@${ticket.author_id}> décris ta demande ici, l’équipe lit ce salon.`)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
@@ -50,6 +50,37 @@ function ticketEmbed(ticket, category) {
);
}
/**
* Guidance posted under the ticket header: what to write, and that an answer can
* take a while. Members often open a ticket with three words and wait.
*/
function ticketHelpEmbed() {
return baseEmbed(COLORS.info)
.setTitle(TONE.advice)
.setDescription(
'Détaille au maximum : tout ce que tu écris ici nous évite de te poser des questions pour rien.',
)
.addFields(
{
name: 'Ce qui nous aide',
value: bullets([
'ce que tu voulais faire, et ce qui s’est passé à la place',
'les étapes pour reproduire le problème, une par une',
'le message d’erreur exact, en photo ou recopié tel quel',
'ta version de l’OS, et ce que tu viens d’installer',
]),
},
{
name: 'Ça peut prendre un peu de temps',
value: bullets([
'ce salon est privé : toi, l’équipe et les personnes que vous ajoutez y voient ces messages',
'l’équipe répond ici, donc ne cherche pas ailleurs pour suivre ton ticket',
'une fois ta demande réglée, ferme le ticket avec le bouton **Fermer**',
]),
},
);
}
function channelName(categoryId, username) {
const slug = username
.toLowerCase()
@@ -83,9 +114,10 @@ function buildOverwrites(guild, client, category, authorId) {
return overwrites;
}
/** The ticket journal lives in the technical logs salon (`CHANNEL_LOGS_ID`). */
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
if (!env.channels.logs) return null;
const channel = await client.channels.fetch(env.channels.logs).catch(() => null);
return channel?.isSendable() ? channel : null;
}
@@ -94,6 +126,33 @@ async function logTicket(client, embed) {
await channel?.send({ embeds: [embed] });
}
/**
* The category the ticket channels live in (`CATEGORY_TICKETS_ID`), or a message
* saying how to fix it. A panel is useless without it, so both paths ask here.
*/
async function resolveTicketCategory(guild) {
if (!env.channels.ticketCategory) {
throw new UserFacingError(
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
);
}
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (!parent) {
log.warn('Ticket category is unreachable', { categoryId: env.channels.ticketCategory });
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe vers aucun salon accessible : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
if (parent.type !== ChannelType.GuildCategory) {
log.warn('Ticket category is not a category', { categoryId: parent.id, type: parent.type });
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
return parent;
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId);
@@ -107,19 +166,8 @@ export async function createTicket(interaction, categoryId) {
`La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`,
);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError(
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
);
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
const parent = await resolveTicketCategory(guild);
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username),
@@ -157,7 +205,7 @@ export async function createTicket(interaction, categoryId) {
await channel.send({
content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)],
embeds: [ticketEmbed(ticket, category), ticketHelpEmbed()],
components: ticketButtons(),
});
@@ -292,9 +340,164 @@ export async function addParticipant(interaction, userId) {
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] });
}
/** Panel posted by `/ticket setup`: one button, then the category chooser. */
function panelEmbed() {
return baseEmbed(COLORS.ticket)
.setTitle('🎫 Besoin d’aide ?')
.setDescription(
'Ouvre un ticket, choisis la catégorie qui correspond, et écris tout ce que tu sais déjà dedans. ' +
'Le salon est privé : seul toi et l’équipe le voyez.',
)
.addFields({
name: 'Tu peux aussi',
value: bullets([
'fermer ton ticket toi-même quand c’est réglé',
'demander à l’équipe d’ajouter quelqu’un au ticket si besoin',
]),
});
}
const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral });
/** The panel belongs in a text salon, and only works with a usable ticket category. */
async function resolvePanelChannel(interaction) {
const channel = interaction.channel;
if (!channel?.isTextBased?.() || channel.isThread?.()) {
throw new UserFacingError(
'Lance cette commande dans un salon texte : le panneau doit rester dans le salon, pas dans un fil.',
);
}
await resolveTicketCategory(interaction.guild);
return channel;
}
/**
* Posts the ticket panel in the current channel and remembers it.
*
* A panel already published there is deleted first: leaving it would give the
* server two entry points, and the stale one would keep working with an old text.
*/
export async function setupPanel(interaction) {
const channel = await resolvePanelChannel(interaction);
const previous = getTicketPanel({ guildId: interaction.guildId, channelId: channel.id });
if (previous) {
const stale = await channel.messages?.fetch(previous.message_id).catch(() => null);
await stale?.delete().catch((error) => log.debug('Could not delete the previous panel', error));
}
const message = await channel.send({
embeds: [panelEmbed()],
components: ticketPanelButton(),
});
// A bot without “Gérer les messages” still installs the panel.
const pinned = await message
.pin()
.then(() => true)
.catch((error) => {
log.warn('Could not pin the ticket panel', error);
return false;
});
setTicketPanel({
guildId: interaction.guildId,
channelId: channel.id,
messageId: message.id,
createdBy: interaction.user.id,
});
logEvent({
guildId: interaction.guildId,
type: 'ticket.panel.installed',
actorId: interaction.user.id,
payload: { channelId: channel.id },
});
await interaction.reply(
ephemeral({
embeds: [
successEmbed(
pinned
? 'Panneau publié et épinglé dans ce salon. Les membres ouvrent un ticket avec le bouton.'
: 'Panneau publié dans ce salon, mais je n’ai pas pu l’épingler : vérifie mes droits.',
),
],
}),
);
}
/** Removes the panel of the current channel, message included. */
export async function removePanel(interaction) {
const channel = interaction.channel;
const panel = getTicketPanel({ guildId: interaction.guildId, channelId: channel?.id });
if (!panel) {
throw new UserFacingError(
'Ce salon n’a pas de panneau : lance `/ticket setup` ici pour en installer un.',
);
}
const message = await channel.messages?.fetch(panel.message_id).catch(() => null);
await message?.delete().catch((error) => log.debug('Could not delete the panel message', error));
deleteTicketPanel({ guildId: interaction.guildId, channelId: channel.id });
logEvent({
guildId: interaction.guildId,
type: 'ticket.panel.removed',
actorId: interaction.user.id,
payload: { channelId: channel.id },
});
await interaction.reply({
embeds: [successEmbed('Panneau retiré de ce salon.')],
flags: MessageFlags.Ephemeral,
});
}
/** Answers the panel button with the categories this member is allowed to open. */
async function openPanelPicker(interaction) {
const categories = TICKET_CATEGORIES.filter((category) => canUseCategory(interaction.member, category));
if (categories.length === 0) {
await interaction.reply(
ephemeral({
embeds: [
errorEmbed(
'Aucune catégorie de ticket ne t’est ouverte pour l’instant. Demande de l’aide dans le salon, l’équipe te répondra.',
),
],
}),
);
return;
}
await interaction.reply(
ephemeral({
content: 'Choisis la catégorie : le salon s’ouvre ensuite, tu écris ton message dedans.',
components: ticketCategorySelect(categories),
}),
);
}
/** Opens the ticket chosen in the panel select menu, and closes the menu. */
async function pickPanelCategory(interaction) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, interaction.values[0]);
await interaction.editReply({
embeds: [
successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
),
],
});
}
/** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:panel:open':
await openPanelPicker(interaction);
return;
case 'ticket:panel:pick':
await pickPanelCategory(interaction);
return;
case 'ticket:claim':
await claimTicket(interaction);
return;
+37 -1
View File
@@ -1,4 +1,10 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js';
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
StringSelectMenuBuilder,
UserSelectMenuBuilder,
} from 'discord.js';
/** Discord label and custom id limits. */
const LABEL_MAX = 80;
@@ -97,3 +103,33 @@ export function pollButtons(pollId, choices) {
}
return rows;
}
/** Button of the ticket panel posted by `/ticket setup`. */
export function ticketPanelButton() {
return [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ticket:panel:open')
.setLabel('Ouvrir un ticket')
.setStyle(ButtonStyle.Primary),
),
];
}
/** Category chooser shown after pressing the panel button, limited to the member's level. */
export function ticketCategorySelect(categories) {
return [
new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('ticket:panel:pick')
.setPlaceholder('Dans quelle catégorie ?')
.addOptions(
categories.map(({ id, label, description }) => ({
label,
value: id,
description,
})),
),
),
];
}
+39
View File
@@ -217,6 +217,45 @@ export function registerConfigurationRoutes(router) {
}
}
if (params.service === 'gitea-recruitment') {
const url = String(values.GITEA_URL ?? '').replace(/\/+$/, '');
const token =
String(values.GITEA_RECRUITMENT_TOKEN ?? '').trim() || String(values.GITEA_TOKEN ?? '').trim();
if (!url || !token) return { ok: false, detail: 'URL ou jeton de recrutement manquant.' };
try {
const identity = await fetch(`${url}/api/v1/user`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
if (!identity.ok) {
return { ok: false, detail: `Gitea a répondu ${identity.status} au jeton de recrutement.` };
}
const user = await identity.json();
// `/admin/users` is the route recruitment really calls: it proves both the
// account's admin rights and the token's `write:admin` scope.
const admin = await fetch(`${url}/api/v1/admin/users?limit=1`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
if (!admin.ok) {
return {
ok: false,
detail:
user.is_admin === true
? `« ${user.login} » est administrateur, mais le jeton n’a pas la portée \`write:admin\` (Gitea a répondu ${admin.status}).`
: `« ${user.login} » n’est pas administrateur de l’instance : seuls les admins peuvent créer des comptes Gitea.`,
};
}
return {
ok: true,
detail: `Jeton de recrutement valide : « ${user.login} » peut créer des comptes et gérer les équipes.`,
};
} catch (error) {
return { ok: false, detail: `Gitea injoignable : ${error.message}` };
}
}
throw notFound('Service inconnu.');
},
WIZARD,
+36 -10
View File
@@ -73,6 +73,7 @@ export const SECTIONS = Object.freeze([
'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.',
'Pour le recrutement, génère un second jeton depuis un compte **administrateur**, avec `write:admin`, `write:organization`, `read:user` : c’est `GITEA_RECRUITMENT_TOKEN`.',
'Copie le jeton immédiatement : Gitea ne le réaffiche jamais.',
],
},
@@ -223,7 +224,7 @@ export const VARIABLES = Object.freeze([
key: 'CHANNEL_LOGS_ID',
section: 'channels',
label: 'Salon des logs techniques',
help: 'Erreurs et événements techniques du bot.',
help: 'Erreurs, événements techniques du bot et journal des tickets.',
type: 'snowflake',
},
{
@@ -233,13 +234,6 @@ export const VARIABLES = Object.freeze([
help: 'Avertissements, mises en sourdine, 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',
@@ -282,6 +276,13 @@ export const VARIABLES = Object.freeze([
help: 'Catégorie sous laquelle les salons privés de tickets sont créés.',
type: 'snowflake',
},
{
key: 'CHANNEL_GITEA_APPLICATIONS_ID',
section: 'channels',
label: 'Candidatures Gitea',
help: 'Salon où le bot publie les candidatures à rejoindre l’équipe Gitea, avec les boutons Accepter et Refuser. Vide : repli sur `CHANNEL_LOGS_ID`.',
type: 'snowflake',
},
// --- Voice -----------------------------------------------------------------
{
@@ -332,10 +333,18 @@ export const VARIABLES = Object.freeze([
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.',
help: 'Jeton personnel de l’organisation. Portée minimale : lecture des dépôts et écriture des issues. Sert aussi de repli au recrutement quand `GITEA_RECRUITMENT_TOKEN` est vide.',
type: 'secret',
testable: 'gitea',
},
{
key: 'GITEA_RECRUITMENT_TOKEN',
section: 'gitea',
label: 'Jeton de recrutement',
help: 'Jeton d’un compte administrateur de l’instance, réservé à la création des comptes recrutés et à leur ajout dans l’équipe. Portées nécessaires : `write:admin`, `write:organization`, `read:user`. Vide : `GITEA_TOKEN` est utilisé.',
type: 'secret',
testable: 'gitea-recruitment',
},
{
key: 'GITEA_OWNER',
section: 'gitea',
@@ -352,6 +361,23 @@ export const VARIABLES = Object.freeze([
type: 'text',
placeholder: 'FWS-Arch',
},
{
key: 'GITEA_ORG',
section: 'gitea',
label: 'Organisation de recrutement',
help: 'Organisation Gitea où les personnes recrutées sont ajoutées. Vide : `GITEA_OWNER` est utilisée.',
type: 'text',
placeholder: 'FWS',
},
{
key: 'GITEA_DEV_TEAM',
section: 'gitea',
label: 'Équipe des développeurs',
help: 'Équipe de cette organisation où chaque candidature acceptée est ajoutée. Elle doit exister côté Gitea.',
type: 'text',
default: 'Dev',
placeholder: 'Dev',
},
{
key: 'GITEA_TIMEOUT_MS',
section: 'gitea',
@@ -744,7 +770,7 @@ export function crossCheck(values) {
warnings.push('Les webhooks sont activés sans secret : tous les événements Gitea seront rejetés.');
}
if (read('GITEA_TOKEN') && !read('GITEA_URL')) {
if ((read('GITEA_TOKEN') || read('GITEA_RECRUITMENT_TOKEN')) && !read('GITEA_URL')) {
warnings.push('Un jeton Gitea est renseigné sans `GITEA_URL` : les appels API resteront désactivés.');
}
+282
View File
@@ -0,0 +1,282 @@
import assert from 'node:assert/strict';
import { Collection } from 'discord.js';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
claimApplication,
createApplication,
getApplication,
getPendingApplicationByMember,
getPendingApplicationByUsername,
getRecruitmentPanel,
rejectApplication,
releaseApplication,
} from '../src/database/repositories/gitea-recruitment-repository.js';
import {
CATEGORY_NAME,
CHANNEL_NAME,
ensureRecruitmentPanel,
generatePassword,
openApplicationModal,
openRejectionModal,
validateEmail,
validateGiteaUsername,
} from '../src/services/gitea/team-recruitment.js';
/** Gitea team recruitment (M20): panel installation and stored applications. */
const GUILD_ID = 'guild-1';
describe('application answers', () => {
it('generates a long password from an unambiguous alphabet', () => {
const password = generatePassword(24);
assert.equal(password.length, 24);
assert.match(password, /^[A-Za-z0-9!@#$%*-_]+$/);
assert.notEqual(generatePassword(24), generatePassword(24));
});
it('accepts the names Gitea allows', () => {
assert.equal(validateGiteaUsername('damien'), null);
assert.equal(validateGiteaUsername('fws-bot_2.0'), null);
});
it('refuses a name Gitea would reject', () => {
assert.match(validateGiteaUsername(''), /Indique/);
assert.match(validateGiteaUsername('-leading'), /commence/);
assert.match(validateGiteaUsername('has space'), /commence/);
assert.match(validateGiteaUsername('a'.repeat(40)), /39 caractères/);
});
it('checks the e-mail before calling Gitea', () => {
assert.equal(validateEmail('moi@exemple.org'), null);
assert.match(validateEmail('pas-un-email'), /valide/);
assert.match(validateEmail(''), /Indique/);
});
/** Discord rejects more than five inputs, and a modal cannot answer another modal. */
it('asks everything in a single modal of five fields', async () => {
let shown;
await openApplicationModal({
showModal: async (modal) => {
shown = modal.toJSON();
},
});
assert.equal(shown.custom_id, 'gitea-team:form');
assert.equal(shown.components.length, 5);
assert.deepEqual(
shown.components.map((row) => row.components[0].custom_id),
['languages', 'level', 'experience', 'username', 'email'],
);
});
/** A refusal must carry a written reason, not a silent click. */
it('asks the team for a reason when it refuses an application', async () => {
let shown;
await openRejectionModal(
{
showModal: async (modal) => {
shown = modal.toJSON();
},
},
{ id: 7 },
);
assert.equal(shown.custom_id, 'gitea-team:reject:7');
assert.equal(shown.components.length, 1);
assert.equal(shown.components[0].components[0].custom_id, 'reason');
assert.equal(shown.components[0].components[0].style, 2, 'the reason is a paragraph');
assert.equal(shown.components[0].components[0].required, true);
});
});
describe('recruitment repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() =>
getDatabase().exec('DELETE FROM gitea_applications; DELETE FROM gitea_recruitment_panels;'),
);
const apply = (overrides = {}) =>
createApplication({
guildId: GUILD_ID,
userId: 'member-1',
languages: 'JavaScript, Rust',
level: 'Intermédiaire',
experience: 'Je veux aider sur la doc.',
giteaUsername: 'membre-1',
email: 'membre@exemple.org',
...overrides,
});
it('stores a pending application and finds it by member and username', () => {
const id = apply();
assert.equal(getApplication(id).status, 'pending');
assert.equal(getPendingApplicationByMember({ guildId: GUILD_ID, userId: 'member-1' }).id, id);
assert.equal(
getPendingApplicationByUsername({ guildId: GUILD_ID, username: 'MEMBRE-1' }).id,
id,
'Gitea compares usernames without case',
);
});
it('refuses a second pending application from the same member', () => {
apply();
assert.throws(() => apply({ giteaUsername: 'autre' }), /UNIQUE/);
});
it('claims only once, so two clicks cannot create two accounts', () => {
const id = apply();
assert.equal(claimApplication(id, 'staff'), 1);
assert.equal(claimApplication(id, 'other-staff'), 0);
assert.equal(getApplication(id).status, 'accepted');
assert.equal(getApplication(id).reviewed_by, 'staff');
});
it('puts a claimed application back in the queue when Gitea fails', () => {
const id = apply();
claimApplication(id, 'staff');
assert.equal(releaseApplication(id), 1);
assert.equal(getApplication(id).status, 'pending');
assert.equal(getApplication(id).reviewed_by, null);
assert.equal(releaseApplication(id), 0);
});
it('rejects only a pending application', () => {
const id = apply();
assert.equal(rejectApplication(id, 'staff'), 1);
assert.equal(getApplication(id).status, 'rejected');
assert.equal(rejectApplication(id, 'staff'), 0);
});
it('keeps the reason of the refusal for the member', () => {
const id = apply();
rejectApplication(id, 'staff', 'Il manque une présentation sur le salon.');
assert.equal(getApplication(id).rejection_reason, 'Il manque une présentation sur le salon.');
});
it('keeps one panel row per guild and updates it', () => {
assert.equal(getRecruitmentPanel(GUILD_ID), null);
});
});
/** A guild reduced to what installing the panel touches. */
function fakeGuild() {
const state = {
messages: new Map(),
sent: 0,
edits: 0,
nextId: 0,
};
const cache = new Collection();
const channel = ({ id, name, type, parent = null }) => {
const parentId = parent?.id ?? null;
const created = {
id,
name,
type,
parentId,
children: { cache: new Collection() },
isSendable: () => true,
messages: {
fetch: async (messageId) => state.messages.get(messageId) ?? null,
},
send: async (payload) => {
state.sent += 1;
const messageId = `message-${(state.nextId += 1)}`;
const message = {
id: messageId,
payload,
pin: async () => {},
edit: async (next) => {
state.edits += 1;
message.payload = next;
return message;
},
};
state.messages.set(messageId, message);
return message;
},
};
if (parent) parent.children.cache.set(id, created);
cache.set(id, created);
return created;
};
const guild = {
id: GUILD_ID,
channels: {
cache,
fetch: async (channelId) => cache.get(channelId) ?? null,
create: async (options) => {
if (options.type === 4) {
return channel({ id: `category-${(state.nextId += 1)}`, name: options.name, type: options.type });
}
return channel({
id: `channel-${(state.nextId += 1)}`,
name: options.name,
type: options.type,
parent: cache.get(options.parent),
});
},
},
};
return { guild, state, client: { guilds: { fetch: async () => guild } } };
}
describe('recruitment panel', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() =>
getDatabase().exec('DELETE FROM gitea_applications; DELETE FROM gitea_recruitment_panels;'),
);
it('creates the category, the salon and the panel on the first start', async () => {
const { guild, state, client } = fakeGuild();
const panel = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Viens aider !' });
assert.equal(panel.edited, false);
assert.equal(state.sent, 1);
assert.equal(guild.channels.cache.get(panel.categoryId).name, CATEGORY_NAME);
assert.equal(guild.channels.cache.get(panel.channelId).name, CHANNEL_NAME);
assert.equal(guild.channels.cache.get(panel.channelId).parentId, panel.categoryId);
assert.equal(getRecruitmentPanel(GUILD_ID).message_id, panel.messageId);
});
it('edits the existing panel instead of posting a second one', async () => {
const { state, client } = fakeGuild();
const first = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Version 1' });
const second = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Version 2' });
assert.equal(state.sent, 1, 'a second panel message was sent');
assert.equal(state.edits, 1);
assert.equal(second.messageId, first.messageId);
});
it('reuses a category and a salon that already exist by name', async () => {
const { guild, state, client } = fakeGuild();
const category = await guild.channels.create({ name: CATEGORY_NAME, type: 4 });
const salon = await guild.channels.create({
name: CHANNEL_NAME,
type: 0,
parent: category.id,
});
const panel = await ensureRecruitmentPanel(client, { guildId: GUILD_ID, text: 'Salut' });
assert.equal(panel.categoryId, category.id);
assert.equal(panel.channelId, salon.id);
assert.equal(state.sent, 1);
});
});
+301
View File
@@ -0,0 +1,301 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ChannelType, Collection } from 'discord.js';
/**
* Ticket channel creation (M6).
*
* The channels are declared before the modules that read them are loaded, hence the
* dynamic imports: `createTicket` refuses to work without a ticket category, and the
* journal goes to the technical logs salon.
*/
process.env.CATEGORY_TICKETS_ID = '1463259435970461925';
process.env.CHANNEL_LOGS_ID = '1237076782453358745';
process.env.ROLE_STAFF_ID = 'role-staff';
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
const { UserFacingError } = await import('../src/core/errors.js');
const { getTicketPanel } = await import('../src/database/repositories/ticket-repository.js');
const { createTicket, handleTicketComponent, removePanel, setupPanel } =
await import('../src/services/tickets/ticket-service.js');
const CATEGORY_ID = process.env.CATEGORY_TICKETS_ID;
const LOGS_CHANNEL = process.env.CHANNEL_LOGS_ID;
const TICKET_CATEGORY = { id: CATEGORY_ID, type: ChannelType.GuildCategory };
const member = (roleIds = []) => ({
id: 'author-1',
guild: { ownerId: 'owner-1' },
roles: { cache: new Collection(roleIds.map((id) => [id, { id }])) },
});
/** Discord reduced to what opening a ticket touches: the category and the new channel. */
function harness({ parent = TICKET_CATEGORY } = {}) {
const state = {
channelMessages: [],
created: [],
deleted: [],
fetched: [],
journal: [],
pinned: [],
replies: [],
};
const journalChannel = {
isSendable: () => true,
send: async (payload) => state.journal.push(payload),
};
const panelChannel = {
id: 'panel-1',
isTextBased: () => true,
isThread: () => false,
send: async (payload) => {
const message = {
id: `panel-message-${state.channelMessages.length + 1}`,
pin: async () => {
state.pinned.push('panel');
},
delete: async () => {
state.deleted.push(message.id);
},
};
state.channelMessages.push({ ...payload, id: message.id });
return message;
},
messages: {
fetch: async (id) => ({ id, delete: async () => state.deleted.push(id) }),
},
};
const channel = {
id: 'channel-1',
send: async (payload) => state.channelMessages.push(payload),
delete: async () => {},
};
const guild = {
id: 'guild-1',
roles: { everyone: { id: 'everyone' } },
channels: {
fetch: async (id) => {
state.fetched.push(id);
if (id === CATEGORY_ID) return parent;
if (id === LOGS_CHANNEL) return journalChannel;
return null;
},
create: async (options) => {
state.created.push(options);
return channel;
},
},
};
const interaction = {
guild,
guildId: 'guild-1',
client: { user: { id: 'bot-1' }, channels: guild.channels },
user: { id: 'author-1', username: 'Léa', tag: 'Léa#0001' },
member: member([process.env.ROLE_STAFF_ID]),
reply: async (payload) => state.replies.push(payload),
deferReply: async () => {},
editReply: async (payload) => state.replies.push(payload),
};
return { state, interaction, journalChannel, panelChannel };
}
const open = (harness) => createTicket(harness.interaction, 'bug');
const embedsOf = (payload) => payload.embeds.map((embed) => embed.toJSON());
describe('ticket creation', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM tickets'));
it('creates the channel inside the category declared in the environment', async () => {
const test = harness();
await open(test);
assert.equal(test.state.fetched.includes(CATEGORY_ID), true);
assert.equal(test.state.created.length, 1);
assert.equal(test.state.created[0].parent, CATEGORY_ID);
assert.equal(test.state.created[0].type, ChannelType.GuildText);
});
it('posts the ticket header and a guidance embed', async () => {
const test = harness();
await open(test);
assert.equal(test.state.channelMessages.length, 1);
const [header, guidance] = embedsOf(test.state.channelMessages[0]);
assert.match(header.title, /^🎫 Ticket Bug #/);
assert.match(guidance.description, /Détaille au maximum/);
assert.match(guidance.fields[0].value, /étapes pour reproduire/);
assert.match(guidance.fields[1].name, /un peu de temps/);
});
it('writes the journal in the technical logs salon', async () => {
const test = harness();
await open(test);
assert.equal(test.state.journal.length, 1);
assert.equal(test.state.journal[0].embeds[0].toJSON().title, '🎫 Ticket ouvert');
});
it('explains how to fix the environment when the category is missing', async () => {
const test = harness({ parent: null });
await assert.rejects(
() => open(test),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /CATEGORY_TICKETS_ID/);
return true;
},
);
assert.equal(test.state.created.length, 0);
});
it('refuses a category id that points at a plain channel', async () => {
const test = harness({ parent: { id: CATEGORY_ID, type: ChannelType.GuildText } });
await assert.rejects(
() => open(test),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /catégorie Discord/);
return true;
},
);
});
});
describe('ticket panel', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM tickets; DELETE FROM ticket_panels;'));
const panelInteraction = (test) => ({ ...test.interaction, channel: test.panelChannel });
const panelMessage = (test) => test.state.channelMessages.at(-1);
it('publishes and pins the panel, then remembers it', async () => {
const test = harness();
await setupPanel(panelInteraction(test));
const message = panelMessage(test);
assert.match(message.embeds[0].toJSON().title, /Besoin d’aide/);
assert.deepEqual(test.state.pinned, ['panel']);
const panel = getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' });
assert.equal(panel.message_id, message.id);
assert.equal(panel.created_by, 'author-1');
assert.match(test.state.replies.at(-1).embeds[0].toJSON().description, /Panneau publié et épinglé/);
});
it('replaces the previous panel instead of stacking a second one', async () => {
const test = harness();
await setupPanel(panelInteraction(test));
await setupPanel(panelInteraction(test));
assert.deepEqual(test.state.deleted, ['panel-message-1']);
assert.equal(test.state.channelMessages.length, 2);
assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }).message_id, 'panel-message-2');
});
it('keeps the panel when the previous message was deleted by hand', async () => {
const test = harness();
await setupPanel(panelInteraction(test));
await setupPanel(panelInteraction(test));
assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }).message_id, 'panel-message-2');
});
it('refuses to install a panel when the ticket category is unusable', async () => {
const test = harness();
test.interaction.guild.channels.fetch = async () => null;
await assert.rejects(
() => setupPanel(panelInteraction(test)),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /CATEGORY_TICKETS_ID/);
return true;
},
);
assert.equal(test.state.channelMessages.length, 0);
});
it('removes the panel and its message', async () => {
const test = harness();
await setupPanel(panelInteraction(test));
await removePanel(panelInteraction(test));
assert.deepEqual(test.state.deleted, ['panel-message-1']);
assert.equal(getTicketPanel({ guildId: 'guild-1', channelId: 'panel-1' }), null);
});
it('says so when the channel has no panel', async () => {
const test = harness();
await assert.rejects(
() => removePanel(panelInteraction(test)),
(error) => {
assert.ok(error instanceof UserFacingError);
assert.match(error.message, /\/ticket setup/);
return true;
},
);
});
it('offers only the categories the member may open', async () => {
const test = harness();
await handleTicketComponent({
...panelInteraction(test),
customId: 'ticket:panel:open',
member: member([process.env.ROLE_STAFF_ID]),
});
const [row] = test.state.replies.at(-1).components;
const { options } = row.toJSON().components[0];
assert.deepEqual(
options.map((option) => option.value),
['support', 'bug', 'report'],
);
});
it('tells a member with no category to ask in the salon', async () => {
const test = harness();
await handleTicketComponent({
...panelInteraction(test),
customId: 'ticket:panel:open',
member: member([]),
});
const reply = test.state.replies.at(-1);
assert.equal(reply.components, undefined);
assert.match(reply.embeds[0].toJSON().description, /Aucune catégorie/);
});
it('opens the ticket from the chosen category', async () => {
const test = harness();
await handleTicketComponent({
...panelInteraction(test),
customId: 'ticket:panel:pick',
values: ['bug'],
});
assert.equal(test.state.created[0].parent, CATEGORY_ID);
assert.match(test.state.replies.at(-1).embeds[0].toJSON().description, /Ton ticket est ouvert/);
});
});
+16
View File
@@ -37,6 +37,22 @@ describe('env schema', () => {
}
});
it('keeps the recruitment token separate and admin-scoped', () => {
const token = BY_KEY.GITEA_RECRUITMENT_TOKEN;
assert.equal(token.type, 'secret');
assert.equal(token.testable, 'gitea-recruitment');
assert.match(token.help, /write:admin/);
assert.match(token.help, /write:organization/);
assert.match(token.help, /read:user/);
});
it('warns when a Gitea token has no URL to talk to', () => {
const warnings = crossCheck({ GITEA_RECRUITMENT_TOKEN: 'jeton-admin' });
assert.ok(warnings.some((warning) => warning.includes('GITEA_URL')));
});
it('covers the variables the bot refuses to start without', () => {
assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']);
});