From 92405ac6187f674beb95042d015a744c67a25ce7 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:06 +0200 Subject: [PATCH 01/51] fix(notifications): apply the channel overrides set from Discord `/notify set` stores the types listed in `NOTIFICATION_TYPES` (`releases`, `commits`, `pull_requests`) while the webhook handler looks them up under the Gitea event names (`release`, `push`, `pull_request`), so an override chosen from Discord was never found and the environment default always won. Co-Authored-By: Claude Opus 5 (1M context) --- .../notifications/notification-service.js | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/services/notifications/notification-service.js b/src/services/notifications/notification-service.js index 999824a..1e0f5c9 100644 --- a/src/services/notifications/notification-service.js +++ b/src/services/notifications/notification-service.js @@ -16,17 +16,33 @@ const defaultChannels = { community: env.channels.logs, }; +/** + * `/notify` and the dashboard name the types after `NOTIFICATION_TYPES`, while the + * webhook handler names them after the Gitea event. Both spellings must resolve to + * the same channel, otherwise an override set from Discord is never applied (M9-T01). + */ +const TYPE_ALIASES = Object.freeze({ + pull_request: 'pull_requests', + pull_requests: 'pull_request', + push: 'commits', + commits: 'push', + release: 'releases', + releases: 'release', +}); + /** SQLite override first, then the environment default (M9-T01). */ export function resolveChannelId(type, guildId = env.discord.guildId) { try { if (guildId) { - const override = getNotificationChannel(guildId, type); - if (override?.channel_id) return override.channel_id; + for (const candidate of [type, TYPE_ALIASES[type]].filter(Boolean)) { + const override = getNotificationChannel(guildId, candidate); + if (override?.channel_id) return override.channel_id; + } } } catch { // The database is unavailable (tests, early startup): use the environment. } - return defaultChannels[type] ?? null; + return defaultChannels[type] ?? defaultChannels[TYPE_ALIASES[type]] ?? null; } /** Sends a notification payload to the channel configured for its type (M9). */ From e4534d4d50485f7d71e29532ca71a029b95c3338 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:15 +0200 Subject: [PATCH 02/51] feat(config): declare the web dashboard environment variables The dashboard is off by default and listens on the loopback interface: it must be an explicit decision to expose it, not a side effect of upgrading. Co-Authored-By: Claude Opus 5 (1M context) --- .env.example | 27 +++++++++++++++++++++++++++ src/config/env.js | 26 +++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index 1af6ff3..fbc64ce 100644 --- a/.env.example +++ b/.env.example @@ -71,6 +71,33 @@ WEBHOOK_PATH=/webhooks/gitea # Shared secret configured in Gitea > Settings > Webhooks GITEA_WEBHOOK_SECRET= +# --- Tableau de bord web (M16) ----------------------------------------------- +# Site d'administration servi par le bot : `npm run setup` pour l'assistant .env, +# puis http://WEB_HOST:WEB_PORT une fois le bot démarré. +WEB_ENABLED=false +# 127.0.0.1 par défaut : n'expose rien hors de la machine. Mettre 0.0.0.0 seulement +# derrière un reverse proxy HTTPS. +WEB_HOST=127.0.0.1 +WEB_PORT=3080 +# URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord. +# Doit correspondre exactement à une redirection déclarée dans le Developer Portal. +WEB_PUBLIC_URL=http://localhost:3080 +# Clé de signature des cookies de session (64 caractères hex). +# Générer avec : node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" +WEB_SESSION_SECRET= +WEB_SESSION_TTL_HOURS=12 +# Developer Portal > OAuth2 > Client Secret. Requis pour la connexion au tableau de bord. +DISCORD_CLIENT_SECRET= +# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord. +# À vider une fois le .env rempli. +WEB_SETUP_TOKEN= +# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement). +WEB_ALLOW_COMMAND_DEPLOYS=false +# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2). +WEB_ALLOW_RESTART=false +WEB_DEPLOY_TIMEOUT_MS=900000 +WEB_RATE_LIMIT_PER_MINUTE=240 + # --- SQLite (M1-T05) --------------------------------------------------------- DATABASE_PATH=./data/fws-bot.sqlite BACKUP_DIR=./data/backups diff --git a/src/config/env.js b/src/config/env.js index e08c0c7..72d4d98 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -79,6 +79,23 @@ export const env = Object.freeze({ secret: read('GITEA_WEBHOOK_SECRET'), }, + web: { + enabled: readBool('WEB_ENABLED'), + host: read('WEB_HOST', '127.0.0.1'), + port: readInt('WEB_PORT', 3080), + publicUrl: read('WEB_PUBLIC_URL', '').replace(/\/+$/, ''), + sessionSecret: read('WEB_SESSION_SECRET'), + sessionTtlHours: readInt('WEB_SESSION_TTL_HOURS', 12), + oauthClientSecret: read('DISCORD_CLIENT_SECRET'), + setupToken: read('WEB_SETUP_TOKEN'), + // Running shell commands from a browser is the most dangerous capability of the + // dashboard, so it stays off until it is explicitly enabled (M16-T06). + allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'), + allowRestart: readBool('WEB_ALLOW_RESTART'), + deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000), + rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240), + }, + database: { path: read('DATABASE_PATH', './data/fws-bot.sqlite'), backupDir: read('BACKUP_DIR', './data/backups'), @@ -93,7 +110,14 @@ export const env = Object.freeze({ }); /** Values that must never appear in Discord messages or logs. */ -export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean); +export const secrets = [ + env.discord.token, + env.gitea.token, + env.webhook.secret, + env.web.sessionSecret, + env.web.oauthClientSecret, + env.web.setupToken, +].filter(Boolean); export function assertRequiredEnv(keys) { const missing = keys.filter((key) => !read(key)); From 4b0737a51224f7ba71426be0896f1d61335ed660 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:15 +0200 Subject: [PATCH 03/51] feat(gitea): add an organization and repository administration client `gitea-client.js` stays focused on the single repository the slash commands talk to. The dashboard addresses any repository of the organization, so its endpoints live apart instead of bloating the command path. Co-Authored-By: Claude Opus 5 (1M context) --- src/services/gitea/gitea-admin.js | 144 ++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 src/services/gitea/gitea-admin.js diff --git a/src/services/gitea/gitea-admin.js b/src/services/gitea/gitea-admin.js new file mode 100644 index 0000000..2ff5589 --- /dev/null +++ b/src/services/gitea/gitea-admin.js @@ -0,0 +1,144 @@ +import { env } from '../../config/env.js'; +import { asList, giteaRequest } from './gitea-client.js'; + +/** + * Administration endpoints used by the web dashboard (M16-T04). + * + * `gitea-client.js` stays focused on the single repository the Discord commands + * talk to; this module addresses any repository of the organization, which is + * what the dashboard needs. + */ + +const query = (params = {}) => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null && value !== '') search.set(key, String(value)); + } + const rendered = search.toString(); + return rendered ? `?${rendered}` : ''; +}; + +const path = (owner, repo) => `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`; + +/** Organization the dashboard manages by default. */ +export const defaultOwner = () => env.gitea.owner; + +export const org = { + get: (owner = defaultOwner()) => giteaRequest(`/orgs/${encodeURIComponent(owner)}`), + update: (payload, owner = defaultOwner()) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}`, { method: 'PATCH', body: payload }), + listRepos: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos${query({ page, limit })}`).then(asList), + listMembers: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/members${query({ page, limit })}`).then(asList), + listTeams: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/teams${query({ page, limit })}`).then(asList), + listTeamMembers: (teamId) => giteaRequest(`/teams/${teamId}/members`).then(asList), + listLabels: ({ owner = defaultOwner(), limit = 100 } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/labels${query({ limit })}`).then(asList), + listHooks: ({ owner = defaultOwner() } = {}) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList), + createRepo: (payload, owner = defaultOwner()) => + giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }), + /** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */ + whoami: () => giteaRequest('/user'), +}; + +export const repos = { + get: (owner, repo) => giteaRequest(path(owner, repo)), + update: (owner, repo, payload) => giteaRequest(path(owner, repo), { method: 'PATCH', body: payload }), + remove: (owner, repo) => giteaRequest(path(owner, repo), { method: 'DELETE' }), + + listBranches: (owner, repo, { page = 1, limit = 50 } = {}) => + giteaRequest(`${path(owner, repo)}/branches${query({ page, limit })}`).then(asList), + createBranch: (owner, repo, { newBranchName, oldBranchName }) => + giteaRequest(`${path(owner, repo)}/branches`, { + method: 'POST', + body: { new_branch_name: newBranchName, old_branch_name: oldBranchName }, + }), + removeBranch: (owner, repo, branch) => + giteaRequest(`${path(owner, repo)}/branches/${encodeURIComponent(branch)}`, { method: 'DELETE' }), + listTags: (owner, repo, { limit = 50 } = {}) => + giteaRequest(`${path(owner, repo)}/tags${query({ limit })}`).then(asList), + listCommits: (owner, repo, { sha, page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/commits${query({ sha, page, limit })}`).then(asList), + languages: (owner, repo) => giteaRequest(`${path(owner, repo)}/languages`), + listTopics: (owner, repo) => giteaRequest(`${path(owner, repo)}/topics`), + replaceTopics: (owner, repo, topics) => + giteaRequest(`${path(owner, repo)}/topics`, { method: 'PUT', body: { topics } }), + + listIssues: (owner, repo, { state = 'open', type = 'issues', page = 1, limit = 20, q } = {}) => + giteaRequest(`${path(owner, repo)}/issues${query({ state, type, page, limit, q })}`).then(asList), + createIssue: (owner, repo, { title, body, labels, assignees }) => + giteaRequest(`${path(owner, repo)}/issues`, { method: 'POST', body: { title, body, labels, assignees } }), + updateIssue: (owner, repo, number, payload) => + giteaRequest(`${path(owner, repo)}/issues/${number}`, { method: 'PATCH', body: payload }), + commentIssue: (owner, repo, number, body) => + giteaRequest(`${path(owner, repo)}/issues/${number}/comments`, { method: 'POST', body: { body } }), + listLabels: (owner, repo, { limit = 100 } = {}) => + giteaRequest(`${path(owner, repo)}/labels${query({ limit })}`).then(asList), + + listPulls: (owner, repo, { state = 'open', page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/pulls${query({ state, page, limit })}`).then(asList), + createPull: (owner, repo, { title, body, head, base }) => + giteaRequest(`${path(owner, repo)}/pulls`, { method: 'POST', body: { title, body, head, base } }), + mergePull: (owner, repo, number, { style = 'squash', title, message, deleteBranch = false } = {}) => + giteaRequest(`${path(owner, repo)}/pulls/${number}/merge`, { + method: 'POST', + body: { + Do: style, + MergeTitleField: title, + MergeMessageField: message, + delete_branch_after_merge: deleteBranch, + }, + }), + + listReleases: (owner, repo, { page = 1, limit = 20, draft, preRelease } = {}) => + giteaRequest( + `${path(owner, repo)}/releases${query({ page, limit, draft, 'pre-release': preRelease })}`, + ).then(asList), + getRelease: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/releases/${id}`), + latestRelease: (owner, repo) => giteaRequest(`${path(owner, repo)}/releases/latest`), + createRelease: (owner, repo, { tagName, target, name, body, draft = false, prerelease = false }) => + giteaRequest(`${path(owner, repo)}/releases`, { + method: 'POST', + body: { tag_name: tagName, target_commitish: target, name, body, draft, prerelease }, + }), + updateRelease: (owner, repo, id, payload) => + giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'PATCH', body: payload }), + removeRelease: (owner, repo, id) => + giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'DELETE' }), + + listCollaborators: (owner, repo) => giteaRequest(`${path(owner, repo)}/collaborators`).then(asList), + addCollaborator: (owner, repo, username, permission = 'write') => + giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { + method: 'PUT', + body: { permission }, + }), + removeCollaborator: (owner, repo, username) => + giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { method: 'DELETE' }), + + listHooks: (owner, repo) => giteaRequest(`${path(owner, repo)}/hooks`).then(asList), + createHook: (owner, repo, { url, secret, events, type = 'gitea' }) => + giteaRequest(`${path(owner, repo)}/hooks`, { + method: 'POST', + body: { type, active: true, events, config: { url, content_type: 'json', secret } }, + }), + removeHook: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/hooks/${id}`, { method: 'DELETE' }), + + /** Gitea Actions. Absent before Gitea 1.20, so callers must tolerate a 404. */ + listActionTasks: (owner, repo, { page = 1, limit = 20 } = {}) => + giteaRequest(`${path(owner, repo)}/actions/tasks${query({ page, limit })}`), + dispatchWorkflow: (owner, repo, workflow, { ref, inputs = {} }) => + giteaRequest(`${path(owner, repo)}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, { + method: 'POST', + body: { ref, inputs }, + }), +}; + +/** Splits `FWS/FWS-Arch` into its two parts, rejecting anything else. */ +export function splitRepository(fullName) { + const [owner, repo, ...rest] = String(fullName ?? '').split('/'); + if (!owner || !repo || rest.length > 0) return null; + return { owner, repo }; +} From 5abe713279c55257793c5d8b5ec9168eb6b8b94e Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:15 +0200 Subject: [PATCH 04/51] feat(database): store dashboard sessions, deploy targets and deployments Sessions and API tokens keep only a hash of the value handed to the client, so a database dump cannot be replayed. A deployment denormalises its target name so the history survives the deletion of that target. Co-Authored-By: Claude Opus 5 (1M context) --- src/database/migrations/006-web-dashboard.sql | 80 ++++++++ .../repositories/deploy-repository.js | 176 ++++++++++++++++++ .../repositories/web-session-repository.js | 107 +++++++++++ 3 files changed, 363 insertions(+) create mode 100644 src/database/migrations/006-web-dashboard.sql create mode 100644 src/database/repositories/deploy-repository.js create mode 100644 src/database/repositories/web-session-repository.js diff --git a/src/database/migrations/006-web-dashboard.sql b/src/database/migrations/006-web-dashboard.sql new file mode 100644 index 0000000..53ff029 --- /dev/null +++ b/src/database/migrations/006-web-dashboard.sql @@ -0,0 +1,80 @@ +-- Web dashboard: sessions, machine tokens, deploy targets and deployments (M16) + +-- Browser sessions created by the Discord OAuth2 login (M16-T02). +-- Only the hash of the cookie value is stored, so a database dump cannot be replayed. +CREATE TABLE IF NOT EXISTS web_sessions ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + user_id TEXT, + username TEXT, + display_name TEXT, + avatar TEXT, + access_level INTEGER NOT NULL DEFAULT 0, + source TEXT NOT NULL DEFAULT 'discord' CHECK (source IN ('discord', 'setup', 'token')), + ip TEXT, + user_agent TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_seen_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at); +CREATE INDEX IF NOT EXISTS idx_web_sessions_user ON web_sessions (user_id); + +-- Long lived tokens for scripts and CI calling the dashboard API (M16-T03). +CREATE TABLE IF NOT EXISTS web_api_tokens ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + access_level INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_used_at TEXT, + expires_at TEXT, + revoked_at TEXT +); + +-- Where a release can be deployed: a signed webhook, a local command or a Gitea Action (M16-T06). +CREATE TABLE IF NOT EXISTS deploy_targets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL DEFAULT 'production', + kind TEXT NOT NULL CHECK (kind IN ('webhook', 'command', 'gitea-action')), + config TEXT NOT NULL DEFAULT '{}', + auto_deploy INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_deploy_targets_name ON deploy_targets (guild_id, name); +CREATE INDEX IF NOT EXISTS idx_deploy_targets_repo ON deploy_targets (guild_id, repository); + +-- One row per deployment attempt. `target_name` is denormalised so the history +-- survives the deletion of its target (M16-T07). +CREATE TABLE IF NOT EXISTS deployments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + target_id INTEGER REFERENCES deploy_targets (id) ON DELETE SET NULL, + target_name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL, + ref TEXT, + release_tag TEXT, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'running', 'success', 'failed', 'cancelled')), + source TEXT NOT NULL DEFAULT 'web', + triggered_by TEXT, + log TEXT, + error TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + started_at TEXT, + finished_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_deployments_target ON deployments (guild_id, target_id, id DESC); +CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments (status, id DESC); diff --git a/src/database/repositories/deploy-repository.js b/src/database/repositories/deploy-repository.js new file mode 100644 index 0000000..40b0fcf --- /dev/null +++ b/src/database/repositories/deploy-repository.js @@ -0,0 +1,176 @@ +import { getDatabase } from '../index.js'; + +/** Deploy targets and deployment history of the release pipeline (M16-T06 / M16-T07). */ + +const parseTarget = (row) => + row + ? { + ...row, + config: JSON.parse(row.config), + auto_deploy: Boolean(row.auto_deploy), + enabled: Boolean(row.enabled), + } + : null; + +export function createTarget({ + guildId, + name, + repository, + environment = 'production', + kind, + config = {}, + autoDeploy = false, + enabled = true, + createdBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deploy_targets + (guild_id, name, repository, environment, kind, config, auto_deploy, enabled, created_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + guildId, + name, + repository, + environment, + kind, + JSON.stringify(config), + autoDeploy ? 1 : 0, + enabled ? 1 : 0, + createdBy, + ); + return getTarget(Number(lastInsertRowid)); +} + +export function getTarget(id) { + return parseTarget(getDatabase().prepare('SELECT * FROM deploy_targets WHERE id = ?').get(id) ?? null); +} + +export function listTargets({ guildId, repository = null } = {}) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + return getDatabase() + .prepare(`SELECT * FROM deploy_targets WHERE ${clauses.join(' AND ')} ORDER BY environment, name`) + .all(...params) + .map(parseTarget); +} + +/** Targets eligible for an automatic deployment when a release is published (M16-T08). */ +export function listAutoTargets({ guildId, repository }) { + return getDatabase() + .prepare( + `SELECT * FROM deploy_targets + WHERE guild_id = ? AND repository = ? AND auto_deploy = 1 AND enabled = 1 + ORDER BY environment, name`, + ) + .all(guildId, repository) + .map(parseTarget); +} + +const UPDATABLE = Object.freeze({ + name: (value) => value, + repository: (value) => value, + environment: (value) => value, + kind: (value) => value, + config: (value) => JSON.stringify(value), + auto_deploy: (value) => (value ? 1 : 0), + enabled: (value) => (value ? 1 : 0), +}); + +export function updateTarget(id, patch) { + const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE); + if (entries.length === 0) return getTarget(id); + + const assignments = entries.map(([key]) => `${key} = ?`).join(', '); + const values = entries.map(([key, value]) => UPDATABLE[key](value)); + getDatabase() + .prepare(`UPDATE deploy_targets SET ${assignments}, updated_at = datetime('now') WHERE id = ?`) + .run(...values, id); + return getTarget(id); +} + +export function removeTarget(id) { + return getDatabase().prepare('DELETE FROM deploy_targets WHERE id = ?').run(id).changes; +} + +export function createDeployment({ + guildId, + targetId = null, + targetName, + repository, + environment, + ref = null, + releaseTag = null, + source = 'web', + triggeredBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deployments + (guild_id, target_id, target_name, repository, environment, ref, release_tag, source, triggered_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, targetId, targetName, repository, environment, ref, releaseTag, source, triggeredBy); + return getDeployment(Number(lastInsertRowid)); +} + +export function getDeployment(id) { + return getDatabase().prepare('SELECT * FROM deployments WHERE id = ?').get(id) ?? null; +} + +export function listDeployments({ guildId, targetId = null, repository = null, status = null, limit = 30 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (targetId) { + clauses.push('target_id = ?'); + params.push(targetId); + } + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + if (status) { + clauses.push('status = ?'); + params.push(status); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM deployments WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function markRunning(id) { + return getDatabase() + .prepare("UPDATE deployments SET status = 'running', started_at = datetime('now') WHERE id = ?") + .run(id).changes; +} + +export function finishDeployment(id, { status, log = null, error = null }) { + return getDatabase() + .prepare( + `UPDATE deployments SET status = ?, log = ?, error = ?, finished_at = datetime('now') WHERE id = ?`, + ) + .run(status, log, error, id).changes; +} + +/** Counts per status, used by the dashboard tiles. */ +export function countByStatus(guildId) { + return getDatabase() + .prepare('SELECT status, COUNT(*) AS count FROM deployments WHERE guild_id = ? GROUP BY status') + .all(guildId); +} + +export function lastDeploymentPerEnvironment(guildId) { + return getDatabase() + .prepare( + `SELECT environment, repository, status, release_tag, finished_at, MAX(id) AS id + FROM deployments WHERE guild_id = ? GROUP BY environment, repository ORDER BY environment`, + ) + .all(guildId); +} diff --git a/src/database/repositories/web-session-repository.js b/src/database/repositories/web-session-repository.js new file mode 100644 index 0000000..c0dcc89 --- /dev/null +++ b/src/database/repositories/web-session-repository.js @@ -0,0 +1,107 @@ +import { getDatabase } from '../index.js'; + +/** Browser sessions and machine tokens of the web dashboard (M16-T02 / M16-T03). */ + +export function createSession({ + id, + tokenHash, + userId = null, + username = null, + displayName = null, + avatar = null, + accessLevel = 0, + source = 'discord', + ip = null, + userAgent = null, + expiresAt, +}) { + getDatabase() + .prepare( + `INSERT INTO web_sessions + (id, token_hash, user_id, username, display_name, avatar, access_level, source, ip, user_agent, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(id, tokenHash, userId, username, displayName, avatar, accessLevel, source, ip, userAgent, expiresAt); + return getSession(id); +} + +export function getSession(id) { + return getDatabase().prepare('SELECT * FROM web_sessions WHERE id = ?').get(id) ?? null; +} + +/** Only returns sessions that have not expired, so callers never have to check. */ +export function getLiveSessionByHash(tokenHash) { + return ( + getDatabase() + .prepare("SELECT * FROM web_sessions WHERE token_hash = ? AND expires_at > datetime('now')") + .get(tokenHash) ?? null + ); +} + +export function touchSession(id) { + return getDatabase().prepare("UPDATE web_sessions SET last_seen_at = datetime('now') WHERE id = ?").run(id) + .changes; +} + +export function deleteSession(id) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE id = ?').run(id).changes; +} + +export function deleteSessionsOfUser(userId) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE user_id = ?').run(userId).changes; +} + +export function listSessions(limit = 50) { + return getDatabase() + .prepare( + `SELECT id, user_id, username, display_name, avatar, access_level, source, ip, user_agent, + created_at, last_seen_at, expires_at + FROM web_sessions WHERE expires_at > datetime('now') ORDER BY last_seen_at DESC LIMIT ?`, + ) + .all(limit); +} + +export function purgeExpiredSessions() { + return getDatabase().prepare("DELETE FROM web_sessions WHERE expires_at <= datetime('now')").run().changes; +} + +export function createApiToken({ name, tokenHash, prefix, accessLevel, createdBy = null, expiresAt = null }) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO web_api_tokens (name, token_hash, prefix, access_level, created_by, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(name, tokenHash, prefix, accessLevel, createdBy, expiresAt); + return Number(lastInsertRowid); +} + +export function getLiveApiTokenByHash(tokenHash) { + return ( + getDatabase() + .prepare( + `SELECT * FROM web_api_tokens + WHERE token_hash = ? AND revoked_at IS NULL + AND (expires_at IS NULL OR expires_at > datetime('now'))`, + ) + .get(tokenHash) ?? null + ); +} + +export function touchApiToken(id) { + getDatabase().prepare("UPDATE web_api_tokens SET last_used_at = datetime('now') WHERE id = ?").run(id); +} + +export function listApiTokens() { + return getDatabase() + .prepare( + `SELECT id, name, prefix, access_level, created_by, created_at, last_used_at, expires_at, revoked_at + FROM web_api_tokens ORDER BY id DESC`, + ) + .all(); +} + +export function revokeApiToken(id) { + return getDatabase() + .prepare("UPDATE web_api_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL") + .run(id).changes; +} From e03b184d68c6f7804637532c6f9db7665c635897 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:35 +0200 Subject: [PATCH 05/51] feat(web): add the HTTP layer and Discord-backed sessions Visitors sign in with Discord and inherit the very same access levels as the slash commands, so there is no second permission model to keep in sync. Writes require a header a cross-site form cannot forge, on top of the `SameSite=Lax` cookie, and a bootstrap token opens the configuration wizard alone for the case where no Discord application exists yet. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/auth/discord-oauth.js | 114 ++++++++++++++++++++++++ src/web/auth/guard.js | 30 +++++++ src/web/auth/routes.js | 152 +++++++++++++++++++++++++++++++ src/web/auth/session.js | 158 +++++++++++++++++++++++++++++++++ src/web/http.js | 162 ++++++++++++++++++++++++++++++++++ src/web/router.js | 63 +++++++++++++ src/web/setup-state.js | 32 +++++++ 7 files changed, 711 insertions(+) create mode 100644 src/web/auth/discord-oauth.js create mode 100644 src/web/auth/guard.js create mode 100644 src/web/auth/routes.js create mode 100644 src/web/auth/session.js create mode 100644 src/web/http.js create mode 100644 src/web/router.js create mode 100644 src/web/setup-state.js diff --git a/src/web/auth/discord-oauth.js b/src/web/auth/discord-oauth.js new file mode 100644 index 0000000..bebce57 --- /dev/null +++ b/src/web/auth/discord-oauth.js @@ -0,0 +1,114 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { ExternalApiError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; + +const log = createLogger('web:oauth'); +const DISCORD_API = 'https://discord.com/api/v10'; + +/** + * `identify` names the visitor, `guilds.members.read` reads their roles on the FWS + * guild so the dashboard can apply the very same access levels as the slash + * commands (M16-T02). + */ +const SCOPES = ['identify', 'guilds.members.read']; + +export const redirectUri = () => `${env.web.publicUrl}/auth/callback`; + +/** True when the OAuth2 login can actually run. */ +export function isOauthConfigured() { + return Boolean(env.discord.clientId && env.web.oauthClientSecret && env.web.publicUrl); +} + +export function authorizeUrl(state) { + const params = new URLSearchParams({ + client_id: env.discord.clientId, + response_type: 'code', + redirect_uri: redirectUri(), + scope: SCOPES.join(' '), + state, + prompt: 'none', + }); + return `https://discord.com/oauth2/authorize?${params}`; +} + +async function discordFetch(endpoint, options = {}) { + const response = await fetch(`${DISCORD_API}${endpoint}`, { + ...options, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { + const error = new ExternalApiError('discord', `${endpoint} failed with ${response.status}`); + error.status = response.status; + throw error; + } + return response.status === 204 ? null : response.json(); +} + +export async function exchangeCode(code) { + const body = new URLSearchParams({ + client_id: env.discord.clientId, + client_secret: env.web.oauthClientSecret, + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri(), + }); + + return discordFetch('/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); +} + +/** Best effort cleanup: the dashboard never needs the user token again. */ +export async function revokeToken(accessToken) { + const body = new URLSearchParams({ + client_id: env.discord.clientId, + client_secret: env.web.oauthClientSecret, + token: accessToken, + }); + await discordFetch('/oauth2/token/revoke', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }).catch((error) => log.debug('Token revocation failed', error)); +} + +export function fetchUser(accessToken) { + return discordFetch('/users/@me', { headers: { Authorization: `Bearer ${accessToken}` } }); +} + +/** Returns null when the visitor is not a member of the guild. */ +export async function fetchGuildMember(accessToken, guildId) { + try { + return await discordFetch(`/users/@me/guilds/${guildId}/member`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + } catch (error) { + if (error.status === 404 || error.status === 403) return null; + throw error; + } +} + +/** + * Same ladder as `core/permissions.js`, applied to the raw role ids returned by + * the OAuth2 member endpoint (which has no discord.js `GuildMember` to offer). + */ +export function resolveAccessLevel({ member, userId, guildOwnerId, roles = env.roles }) { + if (userId && guildOwnerId && userId === guildOwnerId) return ACCESS_LEVELS.OWNER; + if (!member) return null; + + const owned = new Set(member.roles ?? []); + const has = (roleId) => Boolean(roleId) && owned.has(roleId); + if (has(roles.owner)) return ACCESS_LEVELS.OWNER; + if (has(roles.dev)) return ACCESS_LEVELS.DEV; + if (has(roles.staff)) return ACCESS_LEVELS.STAFF; + return ACCESS_LEVELS.USER; +} + +export function avatarUrl(user) { + if (!user?.id) return null; + if (!user.avatar) return `https://cdn.discordapp.com/embed/avatars/${(BigInt(user.id) >> 22n) % 6n}.png`; + return `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128`; +} diff --git a/src/web/auth/guard.js b/src/web/auth/guard.js new file mode 100644 index 0000000..9320ae8 --- /dev/null +++ b/src/web/auth/guard.js @@ -0,0 +1,30 @@ +import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; +import { forbidden, unauthorized } from '../http.js'; + +/** + * Route level access control (M16-T03). + * + * A route declares `{ access: ACCESS_LEVELS.DEV }`. Two exceptions exist: + * - `public: true` skips authentication entirely (login page, health check); + * - `setup: true` marks the routes a bootstrap session may reach. Bootstrap + * sessions exist before Discord is configured, so they are deliberately + * confined to the configuration wizard. + */ +export function authorize(actor, options = {}) { + if (options.public) return; + + if (!actor) throw unauthorized(); + + if (actor.source === 'setup' && !options.setup) { + throw forbidden("Session d'amorçage : seule la configuration est accessible"); + } + + const required = options.access ?? ACCESS_LEVELS.OWNER; + if (actor.accessLevel < required) { + throw forbidden(`Niveau ${ACCESS_LABELS[required]} requis pour cette action`); + } +} + +export function canReach(accessLevel, required) { + return accessLevel >= required; +} diff --git a/src/web/auth/routes.js b/src/web/auth/routes.js new file mode 100644 index 0000000..c8ed62c --- /dev/null +++ b/src/web/auth/routes.js @@ -0,0 +1,152 @@ +import { randomBytes } from 'node:crypto'; +import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { appendCookie, forbidden, parseCookies, redirect, serializeCookie } from '../http.js'; +import { hasSetupToken, isSetupTokenValid } from '../setup-state.js'; +import { + authorizeUrl, + avatarUrl, + exchangeCode, + fetchGuildMember, + fetchUser, + isOauthConfigured, + resolveAccessLevel, + revokeToken, +} from './discord-oauth.js'; +import { STATE_COOKIE, closeSession, openSession, secureCookies, signState, verifyState } from './session.js'; + +const log = createLogger('web:auth'); + +/** Registers the login, callback, logout and identity routes (M16-T02). */ +export function registerAuthRoutes(router) { + router.get( + '/api/auth/config', + ({ context }) => ({ + oauthConfigured: isOauthConfigured(), + setupAvailable: hasSetupToken(), + setupOnly: context.setupOnly, + guildConfigured: Boolean(env.discord.guildId), + loginUrl: '/auth/login', + }), + { public: true }, + ); + + router.get( + '/auth/login', + ({ response }) => { + if (!isOauthConfigured()) { + redirect(response, '/#/login?error=oauth-not-configured'); + return; + } + const state = signState(randomBytes(16).toString('base64url')); + appendCookie(response, serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies() })); + redirect(response, authorizeUrl(state)); + }, + { public: true }, + ); + + router.get( + '/auth/callback', + async ({ request, response, query, context }) => { + const failure = (reason) => redirect(response, `/#/login?error=${reason}`); + + if (query.get('error')) return failure(query.get('error')); + + const state = query.get('state'); + const expected = parseCookies(request.headers.cookie)[STATE_COOKIE]; + appendCookie(response, serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies() })); + if (!state || state !== expected || !verifyState(state)) return failure('state-mismatch'); + + const code = query.get('code'); + if (!code) return failure('missing-code'); + + let grant; + try { + grant = await exchangeCode(code); + } catch (error) { + log.warn('OAuth2 code exchange failed', error); + return failure('exchange-failed'); + } + + const user = await fetchUser(grant.access_token); + const member = await fetchGuildMember(grant.access_token, env.discord.guildId); + await revokeToken(grant.access_token); + + const guildOwnerId = context.client?.guilds?.cache?.get(env.discord.guildId)?.ownerId ?? null; + const accessLevel = resolveAccessLevel({ member, userId: user.id, guildOwnerId }); + + if (accessLevel === null) { + log.warn('Login refused, user is not a member of the guild', { userId: user.id }); + return failure('not-a-member'); + } + if (accessLevel < ACCESS_LEVELS.STAFF) { + log.warn('Login refused, insufficient level', { userId: user.id, accessLevel }); + return failure('insufficient-level'); + } + + openSession(request, response, { + user: { + id: user.id, + username: user.username, + displayName: member?.nick || user.global_name || user.username, + avatar: avatarUrl(user), + }, + accessLevel, + }); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.login', + actorId: user.id, + payload: { accessLevel }, + }); + redirect(response, '/#/'); + }, + { public: true }, + ); + + /** + * Bootstrap login. Only opens a session confined to the configuration wizard, + * never a full dashboard session (M16-T09). + */ + router.post( + '/api/auth/setup', + ({ request, response, body }) => { + if (!hasSetupToken()) throw forbidden("Aucun jeton d'amorçage n'est configuré"); + if (!isSetupTokenValid(body.token)) throw forbidden("Jeton d'amorçage invalide"); + + openSession(request, response, { + user: { id: null, username: 'setup', displayName: 'Assistant de configuration' }, + accessLevel: ACCESS_LEVELS.OWNER, + source: 'setup', + }); + return { ok: true, source: 'setup' }; + }, + { public: true }, + ); + + router.post('/api/auth/logout', ({ request, response }) => { + closeSession(request, response); + return { ok: true }; + }); + + router.get( + '/api/me', + ({ actor }) => { + if (!actor) return { authenticated: false }; + return { + authenticated: true, + userId: actor.userId, + username: actor.username, + displayName: actor.displayName, + avatar: actor.avatar, + accessLevel: actor.accessLevel, + accessLabel: ACCESS_LABELS[actor.accessLevel], + source: actor.source, + kind: actor.kind, + }; + }, + { public: true }, + ); +} diff --git a/src/web/auth/session.js b/src/web/auth/session.js new file mode 100644 index 0000000..4782d00 --- /dev/null +++ b/src/web/auth/session.js @@ -0,0 +1,158 @@ +import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { + createSession, + deleteSession, + getLiveApiTokenByHash, + getLiveSessionByHash, + purgeExpiredSessions, + touchApiToken, + touchSession, +} from '../../database/repositories/web-session-repository.js'; +import { appendCookie, clientIp, forbidden, parseCookies, serializeCookie } from '../http.js'; + +const log = createLogger('web:auth'); + +export const SESSION_COOKIE = 'fws_session'; +export const STATE_COOKIE = 'fws_oauth_state'; + +/** + * Peppers the session tokens. Without `WEB_SESSION_SECRET` a random key is used, + * which keeps the dashboard usable but logs everyone out on restart. + */ +const pepper = (() => { + if (env.web.sessionSecret) return env.web.sessionSecret; + log.warn('WEB_SESSION_SECRET is not set: sessions will be dropped on every restart'); + return randomBytes(32).toString('hex'); +})(); + +const hash = (value) => createHmac('sha256', pepper).update(value).digest('hex'); + +export const secureCookies = () => env.web.publicUrl.startsWith('https://'); + +export function issueToken() { + return randomBytes(32).toString('base64url'); +} + +/** Signs the OAuth2 `state` so the callback can prove it started the flow. */ +export function signState(value) { + return `${value}.${createHmac('sha256', pepper).update(value).digest('base64url')}`; +} + +export function verifyState(signed) { + const separator = String(signed ?? '').lastIndexOf('.'); + if (separator < 0) return null; + const value = signed.slice(0, separator); + const expected = Buffer.from(createHmac('sha256', pepper).update(value).digest('base64url')); + const received = Buffer.from(signed.slice(separator + 1)); + if (expected.length !== received.length || !timingSafeEqual(expected, received)) return null; + return value; +} + +export function openSession(request, response, { user = {}, accessLevel, source = 'discord' }) { + purgeExpiredSessions(); + + const token = issueToken(); + const ttlSeconds = Math.max(1, env.web.sessionTtlHours) * 3600; + const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19); + + const session = createSession({ + id: randomUUID(), + tokenHash: hash(token), + userId: user.id ?? null, + username: user.username ?? null, + displayName: user.displayName ?? user.global_name ?? user.username ?? null, + avatar: user.avatar ?? null, + accessLevel, + source, + ip: clientIp(request), + userAgent: String(request.headers['user-agent'] ?? '').slice(0, 255), + expiresAt, + }); + + appendCookie( + response, + serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies() }), + ); + log.info('Dashboard session opened', { userId: session.user_id, source, accessLevel }); + return session; +} + +export function closeSession(request, response) { + const token = parseCookies(request.headers.cookie)[SESSION_COOKIE]; + const session = token ? getLiveSessionByHash(hash(token)) : null; + if (session) deleteSession(session.id); + appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies() })); +} + +/** + * Identifies the caller from its session cookie or its `Authorization: Bearer` token. + * Returns null for anonymous requests, the route guard decides what to do with it. + */ +export function authenticate(request) { + const token = parseCookies(request.headers.cookie)[SESSION_COOKIE]; + if (token) { + const session = getLiveSessionByHash(hash(token)); + if (session) { + touchSession(session.id); + return { + kind: 'session', + sessionId: session.id, + userId: session.user_id, + username: session.username, + displayName: session.display_name, + avatar: session.avatar, + accessLevel: session.access_level, + source: session.source, + }; + } + } + + const header = String(request.headers.authorization ?? ''); + if (header.startsWith('Bearer ')) { + const apiToken = getLiveApiTokenByHash(hash(header.slice(7).trim())); + if (apiToken) { + touchApiToken(apiToken.id); + return { + kind: 'api-token', + userId: apiToken.created_by, + username: apiToken.name, + displayName: apiToken.name, + accessLevel: apiToken.access_level, + source: 'token', + }; + } + } + + return null; +} + +export const hashToken = hash; + +/** + * Blocks cross-site writes. Cookies are `SameSite=Lax`, so a cross-origin POST + * cannot carry them; the custom header adds a second barrier that a form post + * cannot forge, and the `Origin` check covers the rest (M16-T02). + */ +export function assertSameOrigin(request, actor) { + if (request.method === 'GET' || request.method === 'HEAD') return; + if (actor?.kind === 'api-token') return; + + if (request.headers['x-requested-with'] !== 'fws-dashboard') { + throw forbidden('Requête rejetée : en-tête X-Requested-With manquant'); + } + + const origin = request.headers.origin; + if (!origin) return; + const host = request.headers.host; + const allowed = new Set([env.web.publicUrl, `http://${host}`, `https://${host}`]); + if (!allowed.has(origin.replace(/\/+$/, ''))) { + throw forbidden('Requête rejetée : origine inattendue'); + } +} + +export const LEVEL_NAMES = Object.freeze( + Object.fromEntries(Object.entries(ACCESS_LEVELS).map(([name, value]) => [value, name])), +); diff --git a/src/web/http.js b/src/web/http.js new file mode 100644 index 0000000..5f9c914 --- /dev/null +++ b/src/web/http.js @@ -0,0 +1,162 @@ +import { createReadStream } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import path from 'node:path'; + +/** Request and response helpers shared by every dashboard route (M16-T01). */ + +const MAX_BODY_BYTES = 2 * 1024 * 1024; + +const MIME_TYPES = Object.freeze({ + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', +}); + +/** + * Sent on every response. The dashboard ships no third-party asset, so the policy + * can stay restricted to `self` without breaking anything. + */ +const SECURITY_HEADERS = Object.freeze({ + 'X-Content-Type-Options': 'nosniff', + 'X-Frame-Options': 'DENY', + 'Referrer-Policy': 'same-origin', + 'Content-Security-Policy': + "default-src 'self'; img-src 'self' data: https://cdn.discordapp.com; " + + "style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; " + + "frame-ancestors 'none'; base-uri 'none'; form-action 'self'", +}); + +export class HttpError extends Error { + constructor(status, message, details = null) { + super(message); + this.name = 'HttpError'; + this.status = status; + this.details = details; + } +} + +export const badRequest = (message, details) => new HttpError(400, message, details); +export const unauthorized = (message = 'Authentification requise') => new HttpError(401, message); +export const forbidden = (message = 'Accès refusé') => new HttpError(403, message); +export const notFound = (message = 'Ressource introuvable') => new HttpError(404, message); + +export function sendJson(response, status, payload) { + const body = JSON.stringify(payload ?? null); + response.writeHead(status, { + ...SECURITY_HEADERS, + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(body), + 'Cache-Control': 'no-store', + }); + response.end(body); +} + +export function sendEmpty(response, status, headers = {}) { + response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end(); +} + +export function redirect(response, location, headers = {}) { + sendEmpty(response, 302, { ...headers, Location: location }); +} + +export function readRawBody(request, limit = MAX_BODY_BYTES) { + return new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > limit) { + reject(new HttpError(413, 'Corps de requête trop volumineux')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks))); + request.on('error', reject); + }); +} + +export async function readJsonBody(request) { + const raw = await readRawBody(request); + if (raw.length === 0) return {}; + try { + const parsed = JSON.parse(raw.toString('utf8')); + if (parsed === null || typeof parsed !== 'object') throw new Error('not an object'); + return parsed; + } catch { + throw badRequest('Corps JSON invalide'); + } +} + +export function parseCookies(header = '') { + const jar = {}; + for (const part of header.split(';')) { + const index = part.indexOf('='); + if (index < 0) continue; + jar[part.slice(0, index).trim()] = decodeURIComponent(part.slice(index + 1).trim()); + } + return jar; +} + +export function serializeCookie(name, value, { maxAge, secure = false, path: cookiePath = '/' } = {}) { + const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${cookiePath}`, 'HttpOnly', 'SameSite=Lax']; + if (secure) parts.push('Secure'); + if (maxAge !== undefined) parts.push(`Max-Age=${Math.floor(maxAge)}`); + return parts.join('; '); +} + +/** Appends a cookie without dropping the ones already queued on the response. */ +export function appendCookie(response, cookie) { + const existing = response.getHeader('Set-Cookie'); + const list = existing ? [].concat(existing) : []; + response.setHeader('Set-Cookie', [...list, cookie]); +} + +/** Client address, trusting `X-Forwarded-For` only for its left-most entry. */ +export function clientIp(request) { + const forwarded = request.headers['x-forwarded-for']; + if (typeof forwarded === 'string' && forwarded.length > 0) return forwarded.split(',')[0].trim(); + return request.socket.remoteAddress ?? ''; +} + +/** + * Serves a file from `root`, refusing anything that escapes it. + * Returns false when the file does not exist, so the caller can fall back. + */ +export async function sendStatic(response, root, requestPath, { fallback = null } = {}) { + const relative = decodeURIComponent(requestPath).replace(/^\/+/, ''); + const resolved = path.resolve(root, relative || 'index.html'); + const target = resolved.startsWith(path.resolve(root)) ? resolved : null; + + let file = target; + if (file) { + const info = await stat(file).catch(() => null); + if (info?.isDirectory()) file = path.join(file, 'index.html'); + else if (!info?.isFile()) file = null; + } + if (!file && fallback) file = path.resolve(root, fallback); + if (!file) return false; + + const info = await stat(file).catch(() => null); + if (!info?.isFile()) return false; + + const extension = path.extname(file).toLowerCase(); + response.writeHead(200, { + ...SECURITY_HEADERS, + 'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream', + 'Content-Length': info.size, + // The SPA shell must never be cached, its modules are revalidated on each load. + 'Cache-Control': extension === '.html' ? 'no-store' : 'no-cache', + }); + createReadStream(file).pipe(response); + return true; +} diff --git a/src/web/router.js b/src/web/router.js new file mode 100644 index 0000000..015d77d --- /dev/null +++ b/src/web/router.js @@ -0,0 +1,63 @@ +import { HttpError, notFound } from './http.js'; + +/** + * Minimal router: `/api/repositories/:owner/:repo` style patterns, no dependency (M16-T01). + * A trailing `*` captures the rest of the path under `params.rest`. + */ + +function compile(pattern) { + const segments = pattern.split('/').filter(Boolean); + return { segments, pattern }; +} + +function match(route, segments) { + const params = {}; + for (const [index, expected] of route.segments.entries()) { + if (expected === '*') { + params.rest = segments.slice(index).join('/'); + return params; + } + const actual = segments[index]; + if (actual === undefined) return null; + if (expected.startsWith(':')) params[expected.slice(1)] = decodeURIComponent(actual); + else if (expected !== actual) return null; + } + return segments.length === route.segments.length ? params : null; +} + +export function createRouter() { + const routes = []; + + const add = (method, pattern, handler, options = {}) => { + routes.push({ method, ...compile(pattern), handler, options }); + }; + + return { + get: (pattern, handler, options) => add('GET', pattern, handler, options), + post: (pattern, handler, options) => add('POST', pattern, handler, options), + put: (pattern, handler, options) => add('PUT', pattern, handler, options), + patch: (pattern, handler, options) => add('PATCH', pattern, handler, options), + delete: (pattern, handler, options) => add('DELETE', pattern, handler, options), + + /** + * Finds the handler for a request. + * Throws 405 when the path exists under another method, which is easier to + * debug from the browser console than a plain 404. + */ + resolve(method, pathname) { + const segments = pathname.split('/').filter(Boolean); + let pathMatched = false; + + for (const route of routes) { + const params = match(route, segments); + if (!params) continue; + pathMatched = true; + if (route.method === method) return { ...route, params }; + } + + throw pathMatched ? new HttpError(405, `Méthode ${method} non autorisée ici`) : notFound(); + }, + + list: () => routes.map((route) => `${route.method} ${route.pattern}`), + }; +} diff --git a/src/web/setup-state.js b/src/web/setup-state.js new file mode 100644 index 0000000..f8a3f4d --- /dev/null +++ b/src/web/setup-state.js @@ -0,0 +1,32 @@ +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import { env } from '../config/env.js'; + +/** + * Bootstrap access to the configuration wizard (M16-T09). + * + * Before `.env` exists there is no Discord application to log in with, so the + * wizard accepts a single shared token: either `WEB_SETUP_TOKEN`, or one + * generated for the lifetime of `npm run setup` and printed in the console. + */ + +let runtimeToken = null; + +export function generateRuntimeSetupToken() { + runtimeToken = randomBytes(24).toString('base64url'); + return runtimeToken; +} + +export function hasSetupToken() { + return Boolean(env.web.setupToken || runtimeToken); +} + +export function isSetupTokenValid(candidate) { + const value = String(candidate ?? ''); + if (value.length === 0) return false; + + return [env.web.setupToken, runtimeToken].filter(Boolean).some((expected) => { + const a = Buffer.from(expected); + const b = Buffer.from(value); + return a.length === b.length && timingSafeEqual(a, b); + }); +} From efaaca35dd152e68806fa43082adc67be9ce69a0 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:35 +0200 Subject: [PATCH 06/51] feat(web): read, validate and write the .env configuration Every variable is described once, with its explanation and the steps to obtain it. The form, the validation and the generated file all derive from that description, so adding a variable to the bot means touching one file. The previous file is backed up before being replaced, and an empty secret means "keep the current value" so a token cannot be wiped by accident. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/services/env-file.js | 160 +++++++ src/web/services/env-schema.js | 739 +++++++++++++++++++++++++++++++++ 2 files changed, 899 insertions(+) create mode 100644 src/web/services/env-file.js create mode 100644 src/web/services/env-schema.js diff --git a/src/web/services/env-file.js b/src/web/services/env-file.js new file mode 100644 index 0000000..a8228a5 --- /dev/null +++ b/src/web/services/env-file.js @@ -0,0 +1,160 @@ +import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { createLogger } from '../../core/logger.js'; +import { BY_KEY, SECTIONS, VARIABLES, isSecret } from './env-schema.js'; + +/** Reading and writing `.env` from the configuration wizard (M16-T09). */ + +const log = createLogger('web:env'); + +export const envFilePath = () => path.resolve(process.cwd(), '.env'); + +/** Parses a `.env` body. Unknown keys are kept so the wizard never loses them. */ +export function parseEnv(content) { + const values = {}; + for (const rawLine of content.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line === '' || line.startsWith('#')) continue; + + const separator = line.indexOf('='); + if (separator < 0) continue; + + const key = line + .slice(0, separator) + .trim() + .replace(/^export\s+/, ''); + let value = line.slice(separator + 1).trim(); + if ( + (value.startsWith('"') && value.endsWith('"') && value.length > 1) || + (value.startsWith("'") && value.endsWith("'") && value.length > 1) + ) { + value = value.slice(1, -1); + } + values[key] = value; + } + return values; +} + +export function readEnvFile(file = envFilePath()) { + if (!existsSync(file)) return { exists: false, values: {}, unknown: {} }; + + const values = parseEnv(readFileSync(file, 'utf8')); + const unknown = Object.fromEntries(Object.entries(values).filter(([key]) => !(key in BY_KEY))); + return { exists: true, values, unknown }; +} + +/** Quotes only when needed, so the file stays readable. */ +function renderValue(value) { + const text = String(value ?? ''); + return /[\s#"'$]/.test(text) ? JSON.stringify(text) : text; +} + +/** + * Rebuilds `.env` from the schema so every variable ships with its explanation. + * Unknown keys are appended at the end rather than dropped. + */ +export function renderEnvFile(values, unknown = {}) { + const lines = [ + '# =============================================================================', + '# FWS-Bot — configuration', + `# Généré par l'assistant du tableau de bord le ${new Date().toISOString()}`, + '# Ne jamais committer ce fichier : il contient des secrets.', + '# =============================================================================', + ]; + + for (const section of SECTIONS) { + const variables = VARIABLES.filter((item) => item.section === section.id); + if (variables.length === 0) continue; + + lines.push('', `# --- ${section.title} ${'-'.repeat(Math.max(3, 72 - section.title.length))}`); + if (section.summary) lines.push(`# ${section.summary}`); + + for (const variable of variables) { + lines.push(`# ${variable.label} — ${variable.help}`); + const value = values[variable.key] ?? variable.default ?? ''; + lines.push(`${variable.key}=${renderValue(value)}`); + } + } + + const extras = Object.entries(unknown); + if (extras.length > 0) { + lines.push('', '# --- Variables conservées telles quelles ---------------------------------'); + for (const [key, value] of extras) lines.push(`${key}=${renderValue(value)}`); + } + + return `${lines.join('\n')}\n`; +} + +/** + * Writes `.env` after backing up the previous version. + * The file is chmod 600: it holds the bot token. + */ +export function writeEnvFile(values, { unknown = {}, file = envFilePath() } = {}) { + let backup = null; + if (existsSync(file)) { + backup = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`; + copyFileSync(file, backup); + } else { + mkdirSync(path.dirname(file), { recursive: true }); + } + + writeFileSync(file, renderEnvFile(values, unknown), { encoding: 'utf8', mode: 0o600 }); + // `writeFileSync` only applies `mode` when it creates the file. + chmodSync(file, 0o600); + + log.info('Configuration file written', { file, backup }); + return { file, backup }; +} + +/** Never sends a secret back to the browser: only whether it is filled in. */ +export function maskValues(values) { + const masked = {}; + for (const variable of VARIABLES) { + const value = values[variable.key] ?? ''; + masked[variable.key] = isSecret(variable.key) ? '' : value; + } + return masked; +} + +export function secretStatus(values) { + return Object.fromEntries( + VARIABLES.filter((item) => item.type === 'secret').map((item) => [ + item.key, + Boolean(String(values[item.key] ?? '').trim()), + ]), + ); +} + +/** + * Merges a submitted patch into the stored values. + * An empty secret means « keep the current one », otherwise clearing a field by + * accident would silently destroy the token. + */ +export function mergeValues(current, patch) { + const merged = { ...current }; + for (const [key, value] of Object.entries(patch)) { + if (!(key in BY_KEY)) continue; + const text = String(value ?? '').trim(); + if (isSecret(key) && text === '') continue; + merged[key] = text; + } + return merged; +} + +/** Human readable summary of what a save would change, secrets never revealed. */ +export function diffValues(current, next) { + return VARIABLES.map((variable) => { + const before = String(current[variable.key] ?? ''); + const after = String(next[variable.key] ?? ''); + if (before === after) return null; + return { + key: variable.key, + section: variable.section, + label: variable.label, + secret: isSecret(variable.key), + restartRequired: Boolean(variable.restartRequired), + before: isSecret(variable.key) ? (before ? '••••••' : '') : before, + after: isSecret(variable.key) ? (after ? '••••••' : '') : after, + }; + }).filter(Boolean); +} diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js new file mode 100644 index 0000000..3c18578 --- /dev/null +++ b/src/web/services/env-schema.js @@ -0,0 +1,739 @@ +/** + * Documented description of every `.env` variable (M16-T09). + * + * This file is the single source of truth of the configuration wizard: the form, + * the explanations, the validation and the generated `.env` all derive from it. + * Adding a variable to the bot means adding it here, nowhere else. + */ + +const SNOWFLAKE = /^\d{17,20}$/; + +/** Wizard steps, in the order the user walks through them. */ +export const SECTIONS = Object.freeze([ + { + id: 'discord', + title: 'Application Discord', + summary: 'Identité du bot. Sans ces trois valeurs, le bot ne démarre pas.', + intro: + 'Une « application » Discord héberge ton bot. Elle se crée en deux minutes et fournit un token (le mot de passe du bot) et un identifiant public.', + steps: [ + 'Ouvre le Discord Developer Portal puis clique sur **New Application**.', + 'Onglet **Bot** → **Reset Token** → copie la valeur : c’est `DISCORD_TOKEN`.', + 'Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent**.', + 'Onglet **General Information** → copie l’**Application ID** : c’est `DISCORD_CLIENT_ID`.', + 'Sur Discord, active **Paramètres → Avancés → Mode développeur**, puis clic droit sur ton serveur → **Copier l’identifiant** : c’est `DISCORD_GUILD_ID`.', + ], + links: [{ label: 'Discord Developer Portal', url: 'https://discord.com/developers/applications' }], + }, + { + id: 'roles', + title: 'Rôles FWS', + summary: 'Qui a le droit de faire quoi, sur Discord comme sur ce tableau de bord.', + intro: + 'Les quatre niveaux d’accès (Owner, Dev, Staff, Membre) sont déduits des rôles Discord. Crée d’abord les rôles dans **Paramètres du serveur → Rôles**, puis colle leur identifiant ici.', + steps: [ + 'Crée les rôles manquants dans **Paramètres du serveur → Rôles**.', + 'Clic droit sur chaque rôle → **Copier l’identifiant**.', + 'Le propriétaire du serveur est toujours Owner, même sans rôle configuré.', + 'Si rien n’est renseigné, tout le monde est considéré comme simple membre.', + ], + }, + { + id: 'channels', + title: 'Salons Discord', + summary: 'Où le bot publie ses messages : accueil, logs, notifications Gitea.', + intro: + 'Chaque identifiant est facultatif : un salon non renseigné désactive simplement la fonctionnalité associée. Clic droit sur un salon → **Copier l’identifiant**.', + steps: [ + 'Crée les salons souhaités (accueil, logs, notifications…).', + 'Clic droit sur chaque salon → **Copier l’identifiant**.', + 'Pour les catégories, clic droit sur la catégorie elle-même.', + 'Ces valeurs peuvent aussi être changées plus tard depuis l’onglet Paramètres, sans redémarrage.', + ], + }, + { + id: 'voice', + title: 'Salons vocaux temporaires', + summary: 'Le salon « rejoindre pour créer » et sa catégorie d’accueil.', + intro: + 'Quand un membre rejoint le salon déclencheur, le bot lui crée un salon vocal personnel, supprimé automatiquement une fois vide.', + steps: [ + 'Crée un salon vocal nommé par exemple « ➕ Créer un salon ».', + 'Copie son identifiant dans `CHANNEL_VOICE_TRIGGER_ID`.', + '(Facultatif) Crée une catégorie qui accueillera les salons générés.', + ], + }, + { + id: 'gitea', + title: 'Gitea', + summary: 'Accès à l’organisation, aux dépôts, aux issues et aux releases.', + intro: + 'Le tableau de bord lit et écrit dans Gitea avec un jeton d’accès personnel. Donne-lui le minimum de droits nécessaires.', + steps: [ + 'Connecte-toi à ton instance Gitea avec le compte technique de l’organisation.', + 'Va dans **Paramètres → Applications → Générer un nouveau jeton**.', + 'Coche au minimum `read:organization`, `read:repository`, `write:issue` — ajoute `write:repository` pour créer des releases depuis le site.', + 'Copie le jeton immédiatement : Gitea ne le réaffiche jamais.', + ], + }, + { + id: 'webhook', + title: 'Webhooks Gitea', + summary: 'Notifications temps réel des issues, PR, commits et releases.', + intro: + 'Gitea appelle le bot à chaque événement. La requête est signée en HMAC-SHA256 : sans le secret partagé, elle est rejetée.', + steps: [ + 'Active `WEBHOOK_ENABLED` et choisis un port libre.', + 'Génère un secret aléatoire avec le bouton ci-dessous.', + 'Dans Gitea : **Dépôt (ou organisation) → Paramètres → Webhooks → Ajouter → Gitea**.', + 'URL cible : `https://ton-domaine{WEBHOOK_PATH}`, type de contenu `application/json`, secret identique.', + 'Coche les événements Issues, Pull Requests, Push et Releases.', + ], + }, + { + id: 'web', + title: 'Tableau de bord web', + summary: 'Ce site : accès, connexion Discord et pipeline de déploiement.', + intro: + 'Le tableau de bord réutilise la connexion Discord des membres. Il faut donc déclarer une URL de redirection OAuth2 dans le Developer Portal.', + steps: [ + 'Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.', + 'Toujours dans **OAuth2 → Redirects**, ajoute exactement `{WEB_PUBLIC_URL}/auth/callback`.', + 'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.', + 'Laisse `WEB_HOST` sur `127.0.0.1` et place un reverse proxy HTTPS devant, sauf en développement local.', + ], + links: [{ label: 'OAuth2 du Developer Portal', url: 'https://discord.com/developers/applications' }], + }, + { + id: 'runtime', + title: 'Exécution et journaux', + summary: 'Environnement, verbosité des logs et rétention.', + intro: 'Valeurs sûres par défaut : tu peux passer cette étape et y revenir plus tard.', + steps: [], + }, + { + id: 'database', + title: 'Base de données', + summary: 'Emplacement du fichier SQLite et des sauvegardes.', + intro: + 'La base est un simple fichier. Sauvegarde-la en copiant le dossier `data/` — aucun serveur à installer.', + steps: [], + }, + { + id: 'links', + title: 'Liens publics FWS', + summary: 'Affichés dans les commandes d’aide et sur ce tableau de bord.', + intro: 'Purement cosmétique : ces liens apparaissent dans `/help`, `/fws` et le pied de page du site.', + steps: [], + }, +]); + +/** + * `advanced: true` hides the field behind the « mode avancé » switch. + * `restartRequired: true` warns that the value is only read at startup. + */ +export const VARIABLES = Object.freeze([ + // --- Discord application --------------------------------------------------- + { + key: 'DISCORD_TOKEN', + section: 'discord', + label: 'Token du bot', + help: 'Le mot de passe du bot. Quiconque le possède contrôle le bot : ne le partage jamais et ne le committe jamais.', + type: 'secret', + required: true, + placeholder: 'MTIz...', + restartRequired: true, + testable: 'discord', + }, + { + key: 'DISCORD_CLIENT_ID', + section: 'discord', + label: 'Application ID', + help: 'Identifiant public de l’application. Sert à enregistrer les commandes slash et à construire le lien d’invitation.', + type: 'snowflake', + required: true, + placeholder: '123456789012345678', + restartRequired: true, + }, + { + key: 'DISCORD_GUILD_ID', + section: 'discord', + label: 'Serveur Discord', + help: 'Serveur sur lequel les commandes slash sont enregistrées. L’enregistrement par serveur est instantané, contrairement au global.', + type: 'snowflake', + required: true, + placeholder: '123456789012345678', + restartRequired: true, + }, + + // --- Roles ----------------------------------------------------------------- + { + key: 'ROLE_OWNER_ID', + section: 'roles', + label: 'Rôle Owner', + help: 'Accès complet : configuration, déploiements, suppression de dépôts.', + type: 'snowflake', + }, + { + key: 'ROLE_DEV_ID', + section: 'roles', + label: 'Rôle Dev', + help: 'Gestion des dépôts, des issues, des PR et des releases.', + type: 'snowflake', + }, + { + key: 'ROLE_STAFF_ID', + section: 'roles', + label: 'Rôle Staff', + help: 'Modération, tickets et consultation du tableau de bord.', + type: 'snowflake', + }, + { + key: 'ROLE_MEMBER_ID', + section: 'roles', + label: 'Rôle attribué à l’arrivée', + help: 'Donné automatiquement à chaque nouveau membre du serveur.', + type: 'snowflake', + }, + + // --- Channels -------------------------------------------------------------- + { + key: 'CHANNEL_WELCOME_ID', + section: 'channels', + label: 'Salon d’accueil', + help: 'Message de bienvenue des nouveaux membres.', + type: 'snowflake', + }, + { + key: 'CHANNEL_RULES_ID', + section: 'channels', + label: 'Salon des règles', + help: 'Référencé dans le message de bienvenue.', + type: 'snowflake', + }, + { + key: 'CHANNEL_ANNOUNCEMENTS_ID', + section: 'channels', + label: 'Salon des annonces', + help: 'Cible par défaut des annonces publiées depuis le tableau de bord.', + type: 'snowflake', + }, + { + key: 'CHANNEL_LOGS_ID', + section: 'channels', + label: 'Salon des logs techniques', + help: 'Erreurs et événements techniques du bot.', + type: 'snowflake', + }, + { + key: 'CHANNEL_MOD_LOGS_ID', + section: 'channels', + label: 'Salon des logs de modération', + help: 'Avertissements, exclusions, bannissements.', + type: 'snowflake', + }, + { + key: 'CHANNEL_TICKETS_LOGS_ID', + section: 'channels', + label: 'Salon des logs de tickets', + help: 'Ouverture, prise en charge et clôture des tickets.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_ISSUES_ID', + section: 'channels', + label: 'Notifications — issues', + help: 'Issues Gitea ouvertes, fermées et commentées.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_PULL_REQUESTS_ID', + section: 'channels', + label: 'Notifications — pull requests', + help: 'Ouvertures, mises à jour et merges de PR.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_COMMITS_ID', + section: 'channels', + label: 'Notifications — commits', + help: 'Push sur les branches suivies.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_RELEASES_ID', + section: 'channels', + label: 'Notifications — releases', + help: 'Publication d’une version et résultat des déploiements associés.', + type: 'snowflake', + }, + { + key: 'CHANNEL_NOTIF_ERRORS_ID', + section: 'channels', + label: 'Notifications — erreurs', + help: 'Échecs d’appels API et de déploiement.', + type: 'snowflake', + }, + { + key: 'CATEGORY_TICKETS_ID', + section: 'channels', + label: 'Catégorie des tickets', + help: 'Catégorie sous laquelle les salons privés de tickets sont créés.', + type: 'snowflake', + }, + + // --- Voice ----------------------------------------------------------------- + { + key: 'CHANNEL_VOICE_TRIGGER_ID', + section: 'voice', + label: 'Salon déclencheur', + help: 'Y entrer crée un salon vocal temporaire dont le membre devient propriétaire.', + type: 'snowflake', + }, + { + key: 'CATEGORY_VOICE_ID', + section: 'voice', + label: 'Catégorie d’accueil', + help: 'Où les salons générés sont créés. Vide : dans la même catégorie que le déclencheur.', + type: 'snowflake', + }, + { + key: 'VOICE_EMPTY_GRACE_MS', + section: 'voice', + label: 'Délai avant suppression (ms)', + help: 'Temps d’attente avant de supprimer un salon devenu vide. `0` supprime immédiatement.', + type: 'int', + default: '5000', + min: 0, + advanced: true, + }, + { + key: 'BOT_STATUS_INTERVAL_SECONDS', + section: 'voice', + label: 'Rotation des statuts (s)', + help: 'Rythme de rotation de la présence du bot. Modifiable à chaud par `/status interval`.', + type: 'int', + default: '60', + min: 5, + advanced: true, + }, + + // --- Gitea ----------------------------------------------------------------- + { + key: 'GITEA_URL', + section: 'gitea', + label: 'URL de l’instance', + help: 'Racine de l’instance Gitea, sans `/api/v1` ni barre oblique finale.', + type: 'url', + placeholder: 'https://gitea.exemple.org', + }, + { + key: 'GITEA_TOKEN', + section: 'gitea', + label: 'Jeton d’accès', + help: 'Jeton personnel de l’organisation. Portée minimale : lecture des dépôts et écriture des issues.', + type: 'secret', + testable: 'gitea', + }, + { + key: 'GITEA_OWNER', + section: 'gitea', + label: 'Organisation', + help: 'Nom de l’organisation propriétaire des dépôts, tel qu’il apparaît dans les URL.', + type: 'text', + placeholder: 'FWS', + }, + { + key: 'GITEA_REPO', + section: 'gitea', + label: 'Dépôt principal', + help: 'Dépôt visé par défaut par les commandes Discord `/issue` et `/pr`.', + type: 'text', + placeholder: 'FWS-Arch', + }, + { + key: 'GITEA_TIMEOUT_MS', + section: 'gitea', + label: 'Délai d’expiration (ms)', + help: 'Au-delà, l’appel est abandonné puis réessayé.', + type: 'int', + default: '10000', + min: 1000, + advanced: true, + }, + { + key: 'GITEA_MAX_RETRIES', + section: 'gitea', + label: 'Tentatives supplémentaires', + help: 'Uniquement sur les erreurs transitoires (délai dépassé, 429, 5xx).', + type: 'int', + default: '2', + min: 0, + advanced: true, + }, + + // --- Webhooks -------------------------------------------------------------- + { + key: 'WEBHOOK_ENABLED', + section: 'webhook', + label: 'Activer la réception des webhooks', + help: 'Démarre le serveur HTTP qui reçoit les événements Gitea.', + type: 'bool', + default: 'false', + restartRequired: true, + }, + { + key: 'WEBHOOK_HOST', + section: 'webhook', + label: 'Interface d’écoute', + help: '`0.0.0.0` écoute sur toutes les interfaces, `127.0.0.1` seulement en local.', + type: 'text', + default: '0.0.0.0', + advanced: true, + restartRequired: true, + }, + { + key: 'WEBHOOK_PORT', + section: 'webhook', + label: 'Port', + help: 'Port du serveur de webhooks. Peut être identique à celui du tableau de bord : les deux partagent alors le même serveur.', + type: 'int', + default: '3000', + min: 1, + max: 65535, + restartRequired: true, + }, + { + key: 'WEBHOOK_PATH', + section: 'webhook', + label: 'Chemin d’écoute', + help: 'Chemin exact à configurer côté Gitea.', + type: 'text', + default: '/webhooks/gitea', + pattern: '^/[\\w\\-/]*$', + advanced: true, + restartRequired: true, + }, + { + key: 'GITEA_WEBHOOK_SECRET', + section: 'webhook', + label: 'Secret partagé', + help: 'Doit être strictement identique à celui saisi dans Gitea. Une signature invalide fait rejeter l’événement.', + type: 'secret', + generator: 'hex32', + }, + + // --- Web dashboard --------------------------------------------------------- + { + key: 'WEB_ENABLED', + section: 'web', + label: 'Activer le tableau de bord', + help: 'Sert ce site depuis le processus du bot.', + type: 'bool', + default: 'false', + restartRequired: true, + }, + { + key: 'WEB_HOST', + section: 'web', + label: 'Interface d’écoute', + help: 'Garde `127.0.0.1` et place un reverse proxy HTTPS devant. `0.0.0.0` expose le site sur le réseau.', + type: 'text', + default: '127.0.0.1', + restartRequired: true, + }, + { + key: 'WEB_PORT', + section: 'web', + label: 'Port', + help: 'Port d’écoute du tableau de bord.', + type: 'int', + default: '3080', + min: 1, + max: 65535, + restartRequired: true, + }, + { + key: 'WEB_PUBLIC_URL', + section: 'web', + label: 'URL publique', + help: 'URL par laquelle les membres accèdent au site. La redirection OAuth2 à déclarer est cette URL suivie de `/auth/callback`.', + type: 'url', + placeholder: 'https://bot.exemple.org', + restartRequired: true, + }, + { + key: 'DISCORD_CLIENT_SECRET', + section: 'web', + label: 'Client Secret OAuth2', + help: 'Developer Portal → OAuth2 → Client Secret. Nécessaire pour connecter les membres au tableau de bord.', + type: 'secret', + restartRequired: true, + }, + { + key: 'WEB_SESSION_SECRET', + section: 'web', + label: 'Clé de signature des sessions', + help: 'Protège les cookies de session. La changer déconnecte tout le monde.', + type: 'secret', + generator: 'hex32', + restartRequired: true, + }, + { + key: 'WEB_SESSION_TTL_HOURS', + section: 'web', + label: 'Durée d’une session (h)', + help: 'Au-delà, l’utilisateur doit se reconnecter.', + type: 'int', + default: '12', + min: 1, + advanced: true, + }, + { + key: 'WEB_SETUP_TOKEN', + section: 'web', + label: 'Jeton d’amorçage', + help: 'Ouvre cet assistant sans compte Discord. À vider une fois la configuration terminée.', + type: 'secret', + generator: 'hex16', + advanced: true, + }, + { + key: 'WEB_ALLOW_COMMAND_DEPLOYS', + section: 'web', + label: 'Autoriser les déploiements par commande', + help: 'Permet d’exécuter une commande shell sur le serveur depuis le site. Réservé au niveau Owner : n’active cela que si tu comprends la portée du risque.', + type: 'bool', + default: 'false', + advanced: true, + restartRequired: true, + }, + { + key: 'WEB_ALLOW_RESTART', + section: 'web', + label: 'Autoriser le redémarrage du bot', + help: 'Affiche un bouton de redémarrage. N’a de sens que derrière un superviseur (systemd, pm2, Docker) qui relance le processus.', + type: 'bool', + default: 'false', + advanced: true, + restartRequired: true, + }, + { + key: 'WEB_DEPLOY_TIMEOUT_MS', + section: 'web', + label: 'Délai maximal d’un déploiement (ms)', + help: 'Au-delà, le déploiement est marqué en échec et la commande interrompue.', + type: 'int', + default: '900000', + min: 1000, + advanced: true, + }, + { + key: 'WEB_RATE_LIMIT_PER_MINUTE', + section: 'web', + label: 'Requêtes API par minute', + help: 'Limite par adresse IP, toutes routes confondues.', + type: 'int', + default: '240', + min: 10, + advanced: true, + restartRequired: true, + }, + + // --- Runtime --------------------------------------------------------------- + { + key: 'NODE_ENV', + section: 'runtime', + label: 'Environnement', + help: '`production` en service réel, `development` en local.', + type: 'enum', + options: ['development', 'production', 'test'], + default: 'development', + restartRequired: true, + }, + { + key: 'LOG_LEVEL', + section: 'runtime', + label: 'Niveau de journalisation', + help: '`debug` est bavard et utile pour diagnostiquer, `info` convient au quotidien.', + type: 'enum', + options: ['debug', 'info', 'warn', 'error'], + default: 'info', + restartRequired: true, + }, + { + key: 'LOG_DIR', + section: 'runtime', + label: 'Dossier des journaux', + help: 'Un fichier JSON par jour y est écrit.', + type: 'path', + default: './logs', + advanced: true, + restartRequired: true, + }, + { + key: 'LOG_RETENTION_DAYS', + section: 'runtime', + label: 'Rétention (jours)', + help: 'Durée de conservation des événements fonctionnels en base.', + type: 'int', + default: '30', + min: 1, + advanced: true, + }, + + // --- Database -------------------------------------------------------------- + { + key: 'DATABASE_PATH', + section: 'database', + label: 'Fichier SQLite', + help: 'Chemin du fichier de base. Le dossier est créé s’il n’existe pas.', + type: 'path', + default: './data/fws-bot.sqlite', + restartRequired: true, + }, + { + key: 'BACKUP_DIR', + section: 'database', + label: 'Dossier des sauvegardes', + help: 'Destination des copies de la base déclenchées depuis le tableau de bord.', + type: 'path', + default: './data/backups', + advanced: true, + }, + + // --- Links ----------------------------------------------------------------- + { + key: 'FWS_WEBSITE_URL', + section: 'links', + label: 'Site web', + help: 'Affiché dans `/fws` et dans le pied de page du tableau de bord.', + type: 'url', + }, + { + key: 'FWS_DOCS_URL', + section: 'links', + label: 'Documentation', + help: 'Lien vers la documentation publique du projet.', + type: 'url', + }, + { + key: 'FWS_DISCORD_INVITE_URL', + section: 'links', + label: 'Invitation Discord', + help: 'Lien d’invitation permanent du serveur.', + type: 'url', + }, + { + key: 'FWS_ARCH_REPO_URL', + section: 'links', + label: 'Dépôt FWS Arch', + help: 'Lien direct vers le dépôt principal.', + type: 'url', + }, +]); + +export const BY_KEY = Object.freeze(Object.fromEntries(VARIABLES.map((item) => [item.key, item]))); + +export const isSecret = (key) => BY_KEY[key]?.type === 'secret'; + +/** Variables the bot refuses to start without. */ +export const requiredKeys = () => VARIABLES.filter((item) => item.required).map((item) => item.key); + +/** + * Validates one value against its declaration. + * Returns null when valid, a French message otherwise. + */ +export function validateValue(key, rawValue) { + const variable = BY_KEY[key]; + if (!variable) return `Variable inconnue : ${key}`; + + const value = String(rawValue ?? '').trim(); + if (value === '') return variable.required ? 'Cette valeur est obligatoire.' : null; + if (value.includes('\n')) return 'Les retours à la ligne ne sont pas autorisés.'; + + switch (variable.type) { + case 'snowflake': + return SNOWFLAKE.test(value) + ? null + : 'Un identifiant Discord est composé de 17 à 20 chiffres (active le mode développeur puis « Copier l’identifiant »).'; + case 'int': { + if (!/^-?\d+$/.test(value)) return 'Un nombre entier est attendu.'; + const parsed = Number.parseInt(value, 10); + if (variable.min !== undefined && parsed < variable.min) return `Minimum : ${variable.min}.`; + if (variable.max !== undefined && parsed > variable.max) return `Maximum : ${variable.max}.`; + return null; + } + case 'bool': + return value === 'true' || value === 'false' ? null : 'Valeur attendue : `true` ou `false`.'; + case 'enum': + return variable.options.includes(value) ? null : `Valeurs possibles : ${variable.options.join(', ')}.`; + case 'url': + try { + const parsed = new URL(value); + return parsed.protocol === 'http:' || parsed.protocol === 'https:' + ? null + : 'L’URL doit commencer par http:// ou https://.'; + } catch { + return 'URL invalide.'; + } + default: + if (variable.pattern && !new RegExp(variable.pattern).test(value)) return 'Format inattendu.'; + return null; + } +} + +/** Validates a whole `{ KEY: value }` map. Returns `{ KEY: message }`. */ +export function validateAll(values) { + const errors = {}; + for (const variable of VARIABLES) { + const message = validateValue(variable.key, values[variable.key] ?? ''); + if (message) errors[variable.key] = message; + } + return errors; +} + +/** Cross-field checks the per-variable rules cannot express. */ +export function crossCheck(values) { + const warnings = []; + const read = (key) => String(values[key] ?? '').trim(); + + if (read('WEB_ENABLED') === 'true') { + if (!read('WEB_PUBLIC_URL')) { + warnings.push( + 'Le tableau de bord est activé mais `WEB_PUBLIC_URL` est vide : la connexion Discord échouera.', + ); + } + if (!read('DISCORD_CLIENT_SECRET')) { + warnings.push('Sans `DISCORD_CLIENT_SECRET`, seul le jeton d’amorçage permet d’ouvrir le site.'); + } + if (!read('WEB_SESSION_SECRET')) { + warnings.push('Sans `WEB_SESSION_SECRET`, toutes les sessions sont perdues à chaque redémarrage.'); + } + if (read('WEB_HOST') === '0.0.0.0' && !read('WEB_PUBLIC_URL').startsWith('https://')) { + warnings.push('`WEB_HOST=0.0.0.0` sans HTTPS expose les cookies de session en clair sur le réseau.'); + } + } + + if (read('WEBHOOK_ENABLED') === 'true' && !read('GITEA_WEBHOOK_SECRET')) { + warnings.push('Les webhooks sont activés sans secret : tous les événements Gitea seront rejetés.'); + } + + if (read('GITEA_TOKEN') && !read('GITEA_URL')) { + warnings.push('Un jeton Gitea est renseigné sans `GITEA_URL` : les appels API resteront désactivés.'); + } + + if (read('WEB_ALLOW_COMMAND_DEPLOYS') === 'true') { + warnings.push( + 'Les déploiements par commande shell sont autorisés : réserve l’accès Owner à des personnes de confiance.', + ); + } + + if (read('WEB_ENABLED') === 'true' && read('WEBHOOK_ENABLED') === 'true') { + if (read('WEB_PORT') === read('WEBHOOK_PORT')) { + warnings.push('Tableau de bord et webhooks partagent le port : un seul serveur HTTP sera démarré.'); + } + } + + return warnings; +} From 611129b23c9e11dc13fb0b951ca02e5caba989e1 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:35 +0200 Subject: [PATCH 07/51] feat(web): run and record release deployments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three kinds of target, ordered by how much they trust the caller: a signed webhook runs nothing locally, a Gitea Action delegates to the forge, and a shell command executes arbitrary code on the bot host — hence the double lock of an environment flag plus the Owner level on that last one. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/services/deploy-service.js | 231 +++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 src/web/services/deploy-service.js diff --git a/src/web/services/deploy-service.js b/src/web/services/deploy-service.js new file mode 100644 index 0000000..3fb62d9 --- /dev/null +++ b/src/web/services/deploy-service.js @@ -0,0 +1,231 @@ +import { spawn } from 'node:child_process'; +import { createHmac } from 'node:crypto'; +import { COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { + createDeployment, + finishDeployment, + listAutoTargets, + markRunning, +} from '../../database/repositories/deploy-repository.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { notify } from '../../services/notifications/notification-service.js'; +import { splitRepository, repos } from '../../services/gitea/gitea-admin.js'; +import { HttpError, badRequest, forbidden } from '../http.js'; + +/** Runs a deployment for a target and records its outcome (M16-T07). */ + +const log = createLogger('web:deploy'); +const MAX_LOG_CHARS = 60_000; + +/** Keeps the tail of a long output: the failure is almost always at the end. */ +const trimLog = (text) => + text.length <= MAX_LOG_CHARS + ? text + : `… (${text.length - MAX_LOG_CHARS} caractères tronqués)\n${text.slice(-MAX_LOG_CHARS)}`; + +export function describeTarget(target) { + switch (target.kind) { + case 'webhook': + return `POST ${target.config.url}`; + case 'command': + return target.config.command; + case 'gitea-action': + return `workflow ${target.config.workflow} sur ${target.config.ref ?? 'main'}`; + default: + return target.kind; + } +} + +/** Rejects a target whose configuration cannot possibly run. */ +export function assertRunnable(target) { + if (!target.enabled) throw badRequest('Cette cible est désactivée.'); + + if (target.kind === 'webhook') { + if (!target.config.url) throw badRequest('Cette cible webhook n’a pas d’URL.'); + return; + } + if (target.kind === 'command') { + if (!env.web.allowCommandDeploys) { + throw forbidden('Les déploiements par commande sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS`).'); + } + if (!target.config.command) throw badRequest('Cette cible n’a pas de commande.'); + return; + } + if (target.kind === 'gitea-action') { + if (!target.config.workflow) throw badRequest('Cette cible n’a pas de workflow.'); + return; + } + throw badRequest(`Type de cible inconnu : ${target.kind}`); +} + +async function runWebhook(target, payload) { + const body = JSON.stringify(payload); + const headers = { 'Content-Type': 'application/json', 'User-Agent': 'FWS-Bot' }; + if (target.config.secret) { + headers['X-FWS-Signature'] = createHmac('sha256', target.config.secret).update(body).digest('hex'); + } + Object.assign(headers, target.config.headers ?? {}); + + const response = await fetch(target.config.url, { + method: target.config.method ?? 'POST', + headers, + body, + signal: AbortSignal.timeout(Math.min(env.web.deployTimeoutMs, 120_000)), + }); + const text = await response.text().catch(() => ''); + + if (!response.ok) { + throw new HttpError(502, `Le webhook a répondu ${response.status}`, trimLog(text)); + } + return `HTTP ${response.status}\n${trimLog(text)}`; +} + +/** + * Runs the configured shell command. Gated by `WEB_ALLOW_COMMAND_DEPLOYS` and by + * the Owner access level: it executes arbitrary code on the bot host. + */ +function runCommand(target, payload) { + return new Promise((resolve, reject) => { + const child = spawn(target.config.command, { + shell: true, + cwd: target.config.cwd || process.cwd(), + env: { + ...process.env, + FWS_DEPLOY_REPOSITORY: payload.repository, + FWS_DEPLOY_ENVIRONMENT: payload.environment, + FWS_DEPLOY_REF: payload.ref ?? '', + FWS_DEPLOY_TAG: payload.releaseTag ?? '', + }, + timeout: env.web.deployTimeoutMs, + }); + + let output = ''; + const collect = (chunk) => { + output += chunk; + if (output.length > MAX_LOG_CHARS * 2) output = output.slice(-MAX_LOG_CHARS); + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + + child.on('error', reject); + child.on('close', (code, signal) => { + const rendered = trimLog(output); + if (code === 0) resolve(rendered); + else reject(new HttpError(500, `La commande s’est terminée avec le code ${code ?? signal}`, rendered)); + }); + }); +} + +async function runGiteaAction(target, payload) { + const parts = splitRepository(target.repository); + if (!parts) throw badRequest(`Dépôt invalide : ${target.repository}`); + + await repos.dispatchWorkflow(parts.owner, parts.repo, target.config.workflow, { + ref: target.config.ref || payload.ref || 'main', + inputs: { ...(target.config.inputs ?? {}), environment: payload.environment }, + }); + return `Workflow ${target.config.workflow} déclenché sur ${target.config.ref || payload.ref || 'main'}.`; +} + +/** + * Executes a deployment end to end: history row, run, outcome, Discord notice. + * Never throws — the caller reads the returned record to know what happened. + */ +export async function runDeployment( + client, + target, + { ref = null, releaseTag = null, source = 'web', triggeredBy = null, guildId } = {}, +) { + assertRunnable(target); + + // The history belongs to the guild that owns the target, not to whichever guild + // the process happens to be configured with. + guildId ??= target.guild_id ?? env.discord.guildId; + + const deployment = createDeployment({ + guildId, + targetId: target.id, + targetName: target.name, + repository: target.repository, + environment: target.environment, + ref, + releaseTag, + source, + triggeredBy, + }); + markRunning(deployment.id); + + const payload = { + deploymentId: deployment.id, + repository: target.repository, + environment: target.environment, + target: target.name, + ref, + releaseTag, + triggeredBy, + source, + }; + + log.info('Deployment started', { id: deployment.id, target: target.name, kind: target.kind }); + + try { + let output; + if (target.kind === 'webhook') output = await runWebhook(target, payload); + else if (target.kind === 'command') output = await runCommand(target, payload); + else output = await runGiteaAction(target, payload); + + finishDeployment(deployment.id, { status: 'success', log: output }); + logEvent({ guildId, type: 'deploy.success', actorId: triggeredBy, payload }); + await announce(client, { ...payload, status: 'success' }); + return { ...deployment, status: 'success', log: output }; + } catch (error) { + const details = error.details ?? error.message; + finishDeployment(deployment.id, { status: 'failed', log: details, error: error.message }); + log.error('Deployment failed', error); + logEvent({ guildId, type: 'deploy.failed', actorId: triggeredBy, payload }); + await announce(client, { ...payload, status: 'failed', error: error.message }); + return { ...deployment, status: 'failed', log: details, error: error.message }; + } +} + +/** Publishes the outcome in the releases channel, errors in the errors channel. */ +async function announce(client, result) { + if (!client) return; + + const success = result.status === 'success'; + const embed = { + title: success + ? `Déploiement réussi — ${result.environment}` + : `Déploiement en échec — ${result.environment}`, + color: success ? COLORS.success : COLORS.error, + fields: [ + { name: 'Dépôt', value: result.repository, inline: true }, + { name: 'Cible', value: result.target, inline: true }, + { name: 'Version', value: result.releaseTag || result.ref || '—', inline: true }, + ], + ...(result.error && { description: `\`\`\`${String(result.error).slice(0, 500)}\`\`\`` }), + timestamp: new Date().toISOString(), + }; + + await notify(client, success ? 'releases' : 'errors', { embeds: [embed] }).catch((error) => + log.warn('Could not publish the deployment notification', error), + ); +} + +/** Fires every auto-deploy target of a repository, one after the other (M16-T08). */ +export async function runAutoDeployments(client, { repository, releaseTag, ref, triggeredBy = null }) { + const guildId = env.discord.guildId; + const targets = listAutoTargets({ guildId, repository }); + const results = []; + + for (const target of targets) { + try { + results.push(await runDeployment(client, target, { ref, releaseTag, source: 'auto', triggeredBy })); + } catch (error) { + log.warn('Auto deployment skipped', { target: target.name, reason: error.message }); + } + } + return results; +} From bf92badb05054d85e2f4db29445bfdd2aa006f4f Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:43 +0200 Subject: [PATCH 08/51] feat(web): expose the dashboard API One module per domain, each route declaring the minimum access level the server enforces before the handler runs. Irreversible actions ask for the exact name to be typed back, and every write lands in `event_logs` with its author so the history says who did what. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/api/community.js | 224 +++++++++++++++ src/web/api/configuration.js | 224 +++++++++++++++ src/web/api/deployments.js | 254 ++++++++++++++++ src/web/api/discord.js | 364 +++++++++++++++++++++++ src/web/api/index.js | 47 +++ src/web/api/logs.js | 96 +++++++ src/web/api/organization.js | 179 ++++++++++++ src/web/api/overview.js | 158 ++++++++++ src/web/api/releases.js | 260 +++++++++++++++++ src/web/api/repositories.js | 541 +++++++++++++++++++++++++++++++++++ src/web/api/settings.js | 366 ++++++++++++++++++++++++ 11 files changed, 2713 insertions(+) create mode 100644 src/web/api/community.js create mode 100644 src/web/api/configuration.js create mode 100644 src/web/api/deployments.js create mode 100644 src/web/api/discord.js create mode 100644 src/web/api/index.js create mode 100644 src/web/api/logs.js create mode 100644 src/web/api/organization.js create mode 100644 src/web/api/overview.js create mode 100644 src/web/api/releases.js create mode 100644 src/web/api/repositories.js create mode 100644 src/web/api/settings.js diff --git a/src/web/api/community.js b/src/web/api/community.js new file mode 100644 index 0000000..4680904 --- /dev/null +++ b/src/web/api/community.js @@ -0,0 +1,224 @@ +import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { countVotes, listPolls } from '../../database/repositories/poll-repository.js'; +import { closeTicket, listTickets } from '../../database/repositories/ticket-repository.js'; +import { listVoiceChannels } from '../../database/repositories/voice-repository.js'; +import { listBotStatuses } from '../../database/repositories/bot-status-repository.js'; +import { closePollById } from '../../services/polls/poll-service.js'; +import { + addBotStatus, + applyStatusIfAlone, + clampRotation, + getRotationSeconds, + removeBotStatus, + saveRotationSeconds, + toggleBotStatus, +} from '../../services/status/bot-status-service.js'; +import { + deleteVoiceChannel, + listTriggerSummaries, + removeVoiceTriggerConfig, + saveVoiceTrigger, + setTriggerEnabled, +} from '../../services/voice/voice-service.js'; +import { badRequest, notFound } from '../http.js'; + +/** Tickets, polls, temporary voice channels and bot presence (M16-T05). */ + +const guildId = () => env.discord.guildId; + +export function registerCommunityRoutes(router) { + // --- Tickets --------------------------------------------------------------- + router.get( + '/api/community/tickets', + ({ query }) => ({ + categories: TICKET_CATEGORIES, + tickets: listTickets({ + guildId: guildId(), + status: query.get('status'), + authorId: query.get('authorId'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200), + }), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/tickets/:id/close', + async ({ params, body, actor, context }) => { + const id = Number.parseInt(params.id, 10); + const reason = String(body.reason ?? '').trim() || 'Clôturé depuis le tableau de bord'; + + const changes = closeTicket(id, { closedBy: actor.userId, reason }); + if (changes === 0) throw notFound('Ticket introuvable ou déjà clôturé.'); + + const ticket = listTickets({ guildId: guildId(), limit: 200 }).find((row) => row.id === id); + if (ticket?.channel_id && context.client) { + const channel = await context.client.channels.fetch(ticket.channel_id).catch(() => null); + await channel?.delete(`Ticket #${id} clôturé depuis le tableau de bord`).catch(() => null); + } + + logEvent({ guildId: guildId(), type: 'ticket.close', actorId: actor.userId, payload: { id, reason } }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Polls ----------------------------------------------------------------- + router.get( + '/api/community/polls', + ({ query }) => ({ + polls: listPolls({ + guildId: guildId(), + status: query.get('status'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100), + }).map((poll) => ({ + ...poll, + choices: JSON.parse(poll.choices), + counts: countVotes(poll.id), + })), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/polls/:id/close', + async ({ params, actor, context }) => { + // `closePollById` raises a `UserFacingError` when the poll is gone or already closed. + const id = Number.parseInt(params.id, 10); + await closePollById(context.client, id); + + logEvent({ guildId: guildId(), type: 'poll.close', actorId: actor.userId, payload: { id } }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Temporary voice channels --------------------------------------------- + router.get( + '/api/community/voice', + ({ context }) => { + const guild = context.client?.guilds?.cache?.get(guildId()); + return { + triggers: listTriggerSummaries(guildId()), + channels: listVoiceChannels(guildId()).map((row) => { + const channel = guild?.channels?.cache?.get(row.channel_id); + return { + ...row, + locked: Boolean(row.locked), + alive: Boolean(channel), + members: channel?.members?.size ?? 0, + }; + }), + defaults: { + triggerId: env.channels.voiceTrigger, + categoryId: env.channels.voiceCategory, + emptyGraceMs: env.voice.emptyGraceMs, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/community/voice/triggers/:triggerId', + ({ params, body, actor }) => { + if (!/^\d{17,20}$/.test(params.triggerId)) throw badRequest('Identifiant de salon invalide.'); + + const trigger = saveVoiceTrigger( + guildId(), + { + triggerId: params.triggerId, + label: body.label === undefined ? undefined : String(body.label), + categoryId: body.categoryId === undefined ? undefined : String(body.categoryId), + template: body.template === undefined ? undefined : String(body.template), + userLimit: body.userLimit === undefined ? undefined : Number.parseInt(body.userLimit, 10), + }, + actor.userId, + ); + return { trigger }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/community/voice/triggers/:triggerId/toggle', + ({ params, body }) => ({ + trigger: setTriggerEnabled(guildId(), params.triggerId, Boolean(body.enabled)), + }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/voice/triggers/:triggerId', + ({ params }) => { + removeVoiceTriggerConfig(guildId(), params.triggerId); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/voice/channels/:channelId', + async ({ params, context, actor }) => { + const channel = await context.client?.channels?.fetch(params.channelId).catch(() => null); + if (!channel) throw notFound('Salon introuvable.'); + + await deleteVoiceChannel(channel, `Supprimé depuis le tableau de bord par ${actor.username}`); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Bot presence ---------------------------------------------------------- + router.get( + '/api/community/statuses', + () => ({ + statuses: listBotStatuses(), + intervalSeconds: getRotationSeconds(guildId()), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/community/statuses', + ({ body, actor, context }) => { + const status = addBotStatus({ + text: String(body.text ?? ''), + type: String(body.type ?? 'watching'), + url: body.url ? String(body.url) : null, + createdBy: actor.userId, + }); + // Applies straight away when it is the only status, like `/status add` does. + if (context.client) applyStatusIfAlone(context.client); + return { status }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/community/statuses/:id', + // The service raises a `UserFacingError` for an unknown id or a no-op toggle. + ({ params, body }) => ({ + status: toggleBotStatus(Number.parseInt(params.id, 10), Boolean(body.enabled)), + }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/community/statuses/:id', + ({ params }) => ({ removed: removeBotStatus(Number.parseInt(params.id, 10)) }), + { access: ACCESS_LEVELS.DEV }, + ); + + router.put( + '/api/community/statuses/interval', + ({ body, actor }) => { + const seconds = clampRotation(Number.parseInt(body.seconds ?? 0, 10), { strict: true }); + saveRotationSeconds(seconds, guildId(), actor.userId); + return { intervalSeconds: seconds, restartRequired: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/configuration.js b/src/web/api/configuration.js new file mode 100644 index 0000000..45139cc --- /dev/null +++ b/src/web/api/configuration.js @@ -0,0 +1,224 @@ +import { randomBytes } from 'node:crypto'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { badRequest, notFound } from '../http.js'; +import { + diffValues, + maskValues, + mergeValues, + readEnvFile, + renderEnvFile, + secretStatus, + writeEnvFile, +} from '../services/env-file.js'; +import { SECTIONS, VARIABLES, crossCheck, requiredKeys, validateAll } from '../services/env-schema.js'; + +/** + * Step by step `.env` wizard (M16-T09). + * + * Reachable by a bootstrap session, because its whole purpose is to run before + * the bot has a working configuration. + */ + +const log = createLogger('web:configuration'); +const WIZARD = { access: ACCESS_LEVELS.OWNER, setup: true }; + +/** Values currently loaded in the process, used to prefill a first run. */ +const runningValues = () => ({ + NODE_ENV: env.nodeEnv, + LOG_LEVEL: env.logLevel, + LOG_DIR: env.logDir, + LOG_RETENTION_DAYS: String(env.logRetentionDays), + DISCORD_CLIENT_ID: env.discord.clientId, + DISCORD_GUILD_ID: env.discord.guildId, + GITEA_URL: env.gitea.url, + GITEA_OWNER: env.gitea.owner, + GITEA_REPO: env.gitea.repo, + DATABASE_PATH: env.database.path, +}); + +function currentValues() { + const file = readEnvFile(); + const defaults = Object.fromEntries( + VARIABLES.filter((variable) => variable.default !== undefined).map((v) => [v.key, v.default]), + ); + return { file, values: { ...defaults, ...runningValues(), ...file.values } }; +} + +function report(values) { + const errors = validateAll(values); + const missing = requiredKeys().filter((key) => !String(values[key] ?? '').trim()); + return { + errors, + warnings: crossCheck(values), + missingRequired: missing, + valid: Object.keys(errors).length === 0, + }; +} + +export function registerConfigurationRoutes(router) { + router.get( + '/api/configuration', + () => { + const { file, values } = currentValues(); + return { + sections: SECTIONS, + variables: VARIABLES, + exists: file.exists, + unknownKeys: Object.keys(file.unknown), + values: maskValues(values), + secrets: secretStatus(values), + ...report(values), + }; + }, + WIZARD, + ); + + /** Live feedback while the form is being filled, nothing is written. */ + router.post( + '/api/configuration/validate', + ({ body }) => { + const { values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + return { ...report(next), diff: diffValues(values, next) }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/preview', + ({ body }) => { + const { file, values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + // Secrets are blanked out: the preview may be copied or screenshotted. + const safe = { ...next }; + for (const variable of VARIABLES) { + if (variable.type === 'secret' && safe[variable.key]) safe[variable.key] = '••••••••'; + } + return { content: renderEnvFile(safe, file.unknown) }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/save', + ({ body, actor }) => { + const { file, values } = currentValues(); + const next = mergeValues(values, body.values ?? {}); + const status = report(next); + + // A partial save is allowed while the wizard is still being walked through, + // but a malformed value never reaches the file. + if (!status.valid && body.force !== true) { + throw badRequest('Certaines valeurs sont invalides.', status.errors); + } + + const diff = diffValues(values, next); + if (diff.length === 0) return { ...status, diff, written: false }; + + const { backup } = writeEnvFile(next, { unknown: file.unknown }); + log.info('Configuration saved from the wizard', { + actor: actor.userId ?? 'setup', + changed: diff.map((entry) => entry.key), + }); + + return { + ...status, + diff, + written: true, + backup, + restartRequired: diff.some((entry) => entry.restartRequired), + }; + }, + WIZARD, + ); + + router.post( + '/api/configuration/generate', + ({ body }) => { + const kind = String(body.kind ?? 'hex32'); + const sizes = { hex16: 16, hex32: 32 }; + if (!(kind in sizes)) throw badRequest('Type de secret inconnu.'); + return { value: randomBytes(sizes[kind]).toString('hex') }; + }, + WIZARD, + ); + + /** + * Tries the credentials the user just typed, before they are written to disk. + * Nothing is stored and the value never appears in the response. + */ + router.post( + '/api/configuration/test/:service', + async ({ params, body }) => { + const values = mergeValues(currentValues().values, body.values ?? {}); + + if (params.service === 'discord') { + const token = String(values.DISCORD_TOKEN ?? ''); + if (!token) return { ok: false, detail: 'Aucun token à tester.' }; + + try { + const response = await fetch('https://discord.com/api/v10/users/@me', { + headers: { Authorization: `Bot ${token}` }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { + return { + ok: false, + detail: + response.status === 401 + ? 'Token refusé par Discord. Vérifie que tu as bien copié le token du bot (et non le client secret).' + : `Discord a répondu ${response.status}.`, + }; + } + const user = await response.json(); + return { + ok: true, + detail: `Token valide : ${user.username} (${user.id}).`, + applicationId: user.id, + }; + } catch (error) { + return { ok: false, detail: `Discord injoignable : ${error.message}` }; + } + } + + if (params.service === 'gitea') { + const url = String(values.GITEA_URL ?? '').replace(/\/+$/, ''); + const token = String(values.GITEA_TOKEN ?? ''); + if (!url || !token) return { ok: false, detail: 'URL ou jeton manquant.' }; + + try { + const response = await fetch(`${url}/api/v1/user`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) return { ok: false, detail: `Gitea a répondu ${response.status}.` }; + + const user = await response.json(); + const owner = String(values.GITEA_OWNER ?? ''); + let detail = `Jeton valide pour « ${user.login} ».`; + let organizationReachable = true; + + if (owner) { + const orgResponse = await fetch(`${url}/api/v1/orgs/${encodeURIComponent(owner)}`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + organizationReachable = orgResponse.ok; + detail += orgResponse.ok + ? ` Organisation « ${owner} » accessible.` + : ` En revanche l’organisation « ${owner} » est inaccessible (${orgResponse.status}).`; + } + // The token itself works: an unreachable organization is a warning, not a failure. + return { ok: true, warning: !organizationReachable, detail }; + } catch (error) { + return { ok: false, detail: `Gitea injoignable : ${error.message}` }; + } + } + + throw notFound('Service inconnu.'); + }, + WIZARD, + ); +} diff --git a/src/web/api/deployments.js b/src/web/api/deployments.js new file mode 100644 index 0000000..719d940 --- /dev/null +++ b/src/web/api/deployments.js @@ -0,0 +1,254 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { + createTarget, + getDeployment, + getTarget, + listDeployments, + listTargets, + removeTarget, + updateTarget, +} from '../../database/repositories/deploy-repository.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { splitRepository } from '../../services/gitea/gitea-admin.js'; +import { badRequest, forbidden, notFound } from '../http.js'; +import { assertRunnable, describeTarget, runDeployment } from '../services/deploy-service.js'; + +/** Deploy targets and deployment history (M16-T06 / M16-T07). */ + +const KINDS = ['webhook', 'command', 'gitea-action']; +const guildId = () => env.discord.guildId; + +/** A target's config may hold a shared secret, which never leaves the server. */ +const publicTarget = (target) => ({ + id: target.id, + name: target.name, + repository: target.repository, + environment: target.environment, + kind: target.kind, + autoDeploy: target.auto_deploy, + enabled: target.enabled, + summary: describeTarget(target), + config: { + url: target.config.url ?? null, + method: target.config.method ?? null, + command: target.config.command ?? null, + cwd: target.config.cwd ?? null, + workflow: target.config.workflow ?? null, + ref: target.config.ref ?? null, + hasSecret: Boolean(target.config.secret), + }, + createdBy: target.created_by, + createdAt: target.created_at, + updatedAt: target.updated_at, +}); + +function readTargetPayload(body, { partial = false } = {}) { + const config = {}; + const payload = {}; + + const kind = body.kind === undefined && partial ? undefined : String(body.kind ?? ''); + if (kind !== undefined) { + if (!KINDS.includes(kind)) throw badRequest(`Type de cible attendu : ${KINDS.join(', ')}.`); + payload.kind = kind; + } + + if (body.name !== undefined) { + const name = String(body.name).trim(); + if (!/^[\w .-]{2,60}$/.test(name)) throw badRequest('Nom de cible invalide (2 à 60 caractères).'); + payload.name = name; + } + + if (body.repository !== undefined) { + const repository = String(body.repository).trim(); + if (!splitRepository(repository)) throw badRequest('Dépôt attendu au format `organisation/depot`.'); + payload.repository = repository; + } + + if (body.environment !== undefined) { + const environment = String(body.environment).trim(); + if (!/^[\w-]{2,30}$/.test(environment)) throw badRequest('Nom d’environnement invalide.'); + payload.environment = environment; + } + + if (body.autoDeploy !== undefined) payload.auto_deploy = Boolean(body.autoDeploy); + if (body.enabled !== undefined) payload.enabled = Boolean(body.enabled); + + if (body.config && typeof body.config === 'object') { + const source = body.config; + if (source.url !== undefined) { + const url = String(source.url).trim(); + if (url && !/^https?:\/\//.test(url)) throw badRequest('L’URL du webhook doit être en http(s).'); + config.url = url; + } + if (source.method !== undefined) { + const method = String(source.method).toUpperCase(); + if (!['POST', 'PUT', 'PATCH'].includes(method)) throw badRequest('Méthode HTTP non autorisée.'); + config.method = method; + } + if (source.secret !== undefined) config.secret = String(source.secret); + if (source.headers !== undefined && typeof source.headers === 'object') config.headers = source.headers; + if (source.command !== undefined) config.command = String(source.command); + if (source.cwd !== undefined) config.cwd = String(source.cwd); + if (source.workflow !== undefined) config.workflow = String(source.workflow); + if (source.ref !== undefined) config.ref = String(source.ref); + if (source.inputs !== undefined && typeof source.inputs === 'object') config.inputs = source.inputs; + payload.config = config; + } + + return payload; +} + +/** Command targets execute shell on the host, so they stay Owner-only. */ +function assertMayManage(actor, kind) { + if (kind !== 'command') return; + if (!env.web.allowCommandDeploys) { + throw forbidden('Les cibles de type commande sont désactivées (`WEB_ALLOW_COMMAND_DEPLOYS`).'); + } + if (actor.accessLevel < ACCESS_LEVELS.OWNER) { + throw forbidden('Seul le niveau Owner peut gérer une cible de type commande.'); + } +} + +export function registerDeploymentRoutes(router) { + router.get( + '/api/deploy/targets', + ({ query }) => ({ + targets: listTargets({ guildId: guildId(), repository: query.get('repository') }).map(publicTarget), + commandDeploysAllowed: env.web.allowCommandDeploys, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/deploy/targets', + ({ body, actor }) => { + const payload = readTargetPayload(body); + if (!payload.name || !payload.repository || !payload.kind) { + throw badRequest('`name`, `repository` et `kind` sont obligatoires.'); + } + assertMayManage(actor, payload.kind); + + const target = createTarget({ + guildId: guildId(), + name: payload.name, + repository: payload.repository, + environment: payload.environment ?? 'production', + kind: payload.kind, + config: payload.config ?? {}, + autoDeploy: payload.auto_deploy ?? false, + enabled: payload.enabled ?? true, + createdBy: actor.userId, + }); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.create', + actorId: actor.userId, + payload: { name: target.name, kind: target.kind }, + }); + return publicTarget(target); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/deploy/targets/:id', + ({ params, body, actor }) => { + const current = getTarget(Number.parseInt(params.id, 10)); + if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + const payload = readTargetPayload(body, { partial: true }); + assertMayManage(actor, payload.kind ?? current.kind); + + // A partial config patch must not wipe the secret already stored. + if (payload.config) payload.config = { ...current.config, ...payload.config }; + + const updated = updateTarget(current.id, payload); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.update', + actorId: actor.userId, + payload: { name: updated.name }, + }); + return publicTarget(updated); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/deploy/targets/:id', + ({ params, actor }) => { + const current = getTarget(Number.parseInt(params.id, 10)); + if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + removeTarget(current.id); + logEvent({ + guildId: guildId(), + type: 'web.deploy.target.delete', + actorId: actor.userId, + payload: { name: current.name }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + /** Dry run: checks the target without contacting anything. */ + router.post( + '/api/deploy/targets/:id/check', + ({ params }) => { + const target = getTarget(Number.parseInt(params.id, 10)); + if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.'); + + try { + assertRunnable(target); + return { ok: true, summary: describeTarget(target) }; + } catch (error) { + return { ok: false, reason: error.message }; + } + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/deploy/targets/:id/run', + async ({ params, body, actor, context }) => { + const target = getTarget(Number.parseInt(params.id, 10)); + if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.'); + assertMayManage(actor, target.kind); + + const deployment = await runDeployment(context.client, target, { + ref: body.ref ? String(body.ref) : null, + releaseTag: body.releaseTag ? String(body.releaseTag) : null, + source: 'web', + triggeredBy: actor.userId, + }); + return deployment; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.get( + '/api/deployments', + ({ query }) => ({ + deployments: listDeployments({ + guildId: guildId(), + repository: query.get('repository'), + status: query.get('status'), + targetId: query.get('targetId') ? Number.parseInt(query.get('targetId'), 10) : null, + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100), + }), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/deployments/:id', + ({ params }) => { + const deployment = getDeployment(Number.parseInt(params.id, 10)); + if (!deployment || deployment.guild_id !== guildId()) throw notFound('Déploiement introuvable.'); + return deployment; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/discord.js b/src/web/api/discord.js new file mode 100644 index 0000000..2153c41 --- /dev/null +++ b/src/web/api/discord.js @@ -0,0 +1,364 @@ +import { ChannelType } from 'discord.js'; +import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { canActOn, getAccessLevel } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + countByAction, + listActions, + recordAction, +} from '../../database/repositories/moderation-repository.js'; +import { + listNotificationChannels, + removeNotificationChannel, + setNotificationChannel, +} from '../../database/repositories/notification-repository.js'; +import { sendModerationLog } from '../../services/moderation/moderation-service.js'; +import { badRequest, forbidden, notFound } from '../http.js'; + +/** Discord server management from the dashboard (M16-T05). */ + +const log = createLogger('web:discord'); +const guildId = () => env.discord.guildId; + +function guildOf(context) { + const guild = context.client?.guilds?.cache?.get(guildId()); + if (!guild) throw badRequest('Le bot n’est connecté à aucun serveur pour l’instant.'); + return guild; +} + +/** Resolves the caller as a guild member so the role hierarchy can be enforced. */ +async function actingMember(guild, actor) { + if (!actor.userId) throw forbidden('Cette action demande une session Discord, pas un jeton d’API.'); + const member = await guild.members.fetch(actor.userId).catch(() => null); + if (!member) throw forbidden('Ton compte n’est plus membre du serveur.'); + return member; +} + +const CHANNEL_KINDS = { + [ChannelType.GuildText]: 'text', + [ChannelType.GuildVoice]: 'voice', + [ChannelType.GuildCategory]: 'category', + [ChannelType.GuildAnnouncement]: 'announcement', + [ChannelType.GuildStageVoice]: 'stage', + [ChannelType.GuildForum]: 'forum', +}; + +const summarizeMember = (member) => ({ + id: member.id, + username: member.user.username, + displayName: member.displayName, + avatar: member.displayAvatarURL({ size: 64 }), + bot: member.user.bot, + joinedAt: member.joinedAt?.toISOString() ?? null, + createdAt: member.user.createdAt?.toISOString() ?? null, + roles: member.roles.cache.filter((role) => role.id !== member.guild.id).map((role) => role.id), + accessLevel: getAccessLevel(member), + accessLabel: ACCESS_LABELS[getAccessLevel(member)], + timeoutUntil: member.communicationDisabledUntil?.toISOString() ?? null, +}); + +export function registerDiscordRoutes(router) { + router.get( + '/api/discord/guild', + async ({ context }) => { + const guild = guildOf(context); + await guild.channels.fetch().catch(() => null); + + return { + id: guild.id, + name: guild.name, + description: guild.description, + icon: guild.iconURL({ size: 256 }), + banner: guild.bannerURL({ size: 512 }), + ownerId: guild.ownerId, + memberCount: guild.memberCount, + createdAt: guild.createdAt?.toISOString() ?? null, + boostTier: guild.premiumTier, + boostCount: guild.premiumSubscriptionCount, + verificationLevel: guild.verificationLevel, + features: guild.features, + channels: guild.channels.cache + .map((channel) => ({ + id: channel.id, + name: channel.name, + kind: CHANNEL_KINDS[channel.type] ?? 'other', + parentId: channel.parentId, + position: channel.rawPosition, + nsfw: channel.nsfw ?? false, + topic: channel.topic ?? null, + })) + .sort((a, b) => a.position - b.position), + roles: guild.roles.cache + .filter((role) => role.id !== guild.id) + .map((role) => ({ + id: role.id, + name: role.name, + color: role.hexColor, + position: role.position, + managed: role.managed, + mentionable: role.mentionable, + memberCount: role.members.size, + })) + .sort((a, b) => b.position - a.position), + mapping: { + roles: env.roles, + channels: env.channels, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/members', + async ({ context, query }) => { + const guild = guildOf(context); + const search = (query.get('q') ?? '').trim().toLowerCase(); + const limit = Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200); + + const members = await guild.members.fetch().catch(() => guild.members.cache); + const matched = members + .filter((member) => + search === '' + ? true + : member.user.username.toLowerCase().includes(search) || + member.displayName.toLowerCase().includes(search) || + member.id === search, + ) + .first(limit); + + return { total: guild.memberCount, members: matched.map(summarizeMember) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/members/:id', + async ({ context, params }) => { + const guild = guildOf(context); + const member = await guild.members.fetch(params.id).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + + return { + ...summarizeMember(member), + history: listActions({ guildId: guild.id, targetId: member.id, limit: 50 }), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/discord/members/:id/roles', + async ({ context, params, body, actor }) => { + const guild = guildOf(context); + const actorMember = await actingMember(guild, actor); + const member = await guild.members.fetch(params.id).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); + + const roleId = String(body.roleId ?? ''); + const role = guild.roles.cache.get(roleId); + if (!role) throw badRequest('Rôle introuvable.'); + if (role.position >= actorMember.roles.highest.position && guild.ownerId !== actorMember.id) { + throw forbidden('Ce rôle est au-dessus du tien.'); + } + + const action = body.action === 'remove' ? 'remove' : 'add'; + if (action === 'add') await member.roles.add(role, `Tableau de bord — ${actor.username}`); + else await member.roles.remove(role, `Tableau de bord — ${actor.username}`); + + recordAction({ + guildId: guild.id, + action: 'role', + moderatorId: actor.userId, + targetId: member.id, + reason: `${action === 'add' ? 'Ajout' : 'Retrait'} du rôle ${role.name} depuis le tableau de bord`, + }); + return { ok: true, roles: summarizeMember(member).roles }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Applies a moderation action, mirroring what the slash commands do (M8). */ + router.post( + '/api/discord/moderation', + async ({ context, body, actor }) => { + const guild = guildOf(context); + const actorMember = await actingMember(guild, actor); + + const action = String(body.action ?? ''); + if (!['warn', 'mute', 'kick', 'ban'].includes(action)) { + throw badRequest('Action attendue : warn, mute, kick ou ban.'); + } + + const member = await guild.members.fetch(String(body.userId ?? '')).catch(() => null); + if (!member) throw notFound('Membre introuvable sur le serveur.'); + if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.'); + + const reason = String(body.reason ?? '').trim() || 'Non précisé'; + const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null; + if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) { + throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.'); + } + + const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`; + if (action === 'mute') await member.timeout(durationMs, audit); + else if (action === 'kick') await member.kick(audit); + else if (action === 'ban') await member.ban({ reason: audit, deleteMessageSeconds: 0 }); + + recordAction({ + guildId: guild.id, + action, + moderatorId: actor.userId, + targetId: member.id, + reason, + durationMs, + }); + logEvent({ + guildId: guild.id, + type: `moderation.${action}`, + actorId: actor.userId, + payload: { targetId: member.id, reason, durationMs, source: 'web' }, + }); + await sendModerationLog(context.client, guild, { + action, + targetId: member.id, + moderatorId: actor.userId, + reason, + durationMs, + }); + + return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/discord/moderation', + ({ query }) => ({ + actions: listActions({ + guildId: guildId(), + targetId: query.get('userId'), + action: query.get('action'), + limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200), + }), + totals: countByAction(guildId()), + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + /** Publishes a message in a channel: announcements, maintenance notices. */ + router.post( + '/api/discord/announce', + async ({ context, body, actor }) => { + const guild = guildOf(context); + const channelId = String(body.channelId ?? '') || env.channels.announcements; + if (!channelId) throw badRequest('Aucun salon de destination.'); + + const channel = await context.client.channels.fetch(channelId).catch(() => null); + if (!channel?.isSendable()) throw badRequest('Salon introuvable ou non accessible en écriture.'); + + const content = String(body.content ?? '').trim(); + const title = String(body.title ?? '').trim(); + if (content === '' && title === '') throw badRequest('Le message est vide.'); + + const payload = body.asEmbed + ? { + embeds: [ + { + title: title || undefined, + description: content || undefined, + color: Number.parseInt(String(body.color ?? '0x1793d1'), 16) || 0x1793d1, + footer: { text: `Publié par ${actor.displayName ?? actor.username}` }, + timestamp: new Date().toISOString(), + }, + ], + } + : { content: title ? `**${title}**\n${content}` : content }; + + const message = await channel.send(payload); + logEvent({ + guildId: guild.id, + type: 'web.announce', + actorId: actor.userId, + payload: { channelId, messageId: message.id }, + }); + log.info('Announcement published from the dashboard', { channelId, actor: actor.userId }); + return { ok: true, messageId: message.id, url: message.url }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Notification routing -------------------------------------------------- + router.get( + '/api/discord/notifications', + () => ({ + overrides: listNotificationChannels(guildId()), + defaults: { + issues: env.channels.notifIssues, + pull_requests: env.channels.notifPullRequests, + commits: env.channels.notifCommits, + releases: env.channels.notifReleases, + errors: env.channels.notifErrors, + announcements: env.channels.announcements, + community: env.channels.logs, + }, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/discord/notifications/:type', + ({ params, body, actor }) => { + const channelId = String(body.channelId ?? '').trim(); + if (channelId === '') { + removeNotificationChannel(guildId(), params.type); + return { ok: true, removed: true }; + } + if (!/^\d{17,20}$/.test(channelId)) throw badRequest('Identifiant de salon invalide.'); + + setNotificationChannel({ + guildId: guildId(), + type: params.type, + channelId, + detailLevel: String(body.detailLevel ?? 'normal'), + }); + logEvent({ + guildId: guildId(), + type: 'web.notifications.update', + actorId: actor.userId, + payload: { type: params.type, channelId }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** Read-only inventory of the loaded slash commands and their required level. */ + router.get( + '/api/discord/commands', + ({ context }) => ({ + commands: [...(context.client?.commands?.values() ?? [])] + .map((command) => { + // `toJSON()` flattens the builder, whose option objects are builders too. + const definition = command.data.toJSON(); + return { + name: definition.name, + description: definition.description, + access: command.access ?? ACCESS_LEVELS.USER, + accessLabel: ACCESS_LABELS[command.access ?? ACCESS_LEVELS.USER], + subcommandAccess: command.subcommandAccess ?? null, + options: (definition.options ?? []).map((option) => ({ + name: option.name, + description: option.description, + type: option.type, + })), + }; + }) + .sort((a, b) => a.name.localeCompare(b.name)), + }), + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/index.js b/src/web/api/index.js new file mode 100644 index 0000000..7705500 --- /dev/null +++ b/src/web/api/index.js @@ -0,0 +1,47 @@ +import { registerAuthRoutes } from '../auth/routes.js'; +import { registerCommunityRoutes } from './community.js'; +import { registerConfigurationRoutes } from './configuration.js'; +import { registerDeploymentRoutes } from './deployments.js'; +import { registerDiscordRoutes } from './discord.js'; +import { registerLogRoutes } from './logs.js'; +import { registerOrganizationRoutes } from './organization.js'; +import { registerOverviewRoutes } from './overview.js'; +import { registerReleaseRoutes } from './releases.js'; +import { registerRepositoryRoutes } from './repositories.js'; +import { registerSettingsRoutes } from './settings.js'; + +/** + * Route registration order matters only for readability: the router matches on + * the full pattern, not on declaration order. + */ +export function registerApiRoutes(router, { setupOnly = false } = {}) { + // Liveness probe for a reverse proxy or an uptime monitor. Registered first so + // it answers even in bootstrap mode, when nothing else is mounted. + router.get( + '/api/health', + ({ context }) => ({ + status: context.client?.isReady?.() ? 'ok' : 'starting', + setupOnly: context.setupOnly, + uptimeMs: Date.now() - context.startedAt, + }), + { public: true }, + ); + + registerAuthRoutes(router); + registerConfigurationRoutes(router); + + // In bootstrap mode the bot is not connected and the database may be empty: + // only the wizard makes sense. + if (setupOnly) return router; + + registerOverviewRoutes(router); + registerOrganizationRoutes(router); + registerRepositoryRoutes(router); + registerReleaseRoutes(router); + registerDeploymentRoutes(router); + registerDiscordRoutes(router); + registerCommunityRoutes(router); + registerSettingsRoutes(router); + registerLogRoutes(router); + return router; +} diff --git a/src/web/api/logs.js b/src/web/api/logs.js new file mode 100644 index 0000000..83a89d6 --- /dev/null +++ b/src/web/api/logs.js @@ -0,0 +1,96 @@ +import { readFile, readdir, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { maskSecrets } from '../../core/logger.js'; +import { getDatabase } from '../../database/index.js'; +import { badRequest, notFound } from '../http.js'; + +/** Functional event log and technical log files (M16-T05). */ + +const LOG_FILE = /^\d{4}-\d{2}-\d{2}\.log$/; + +export function registerLogRoutes(router) { + router.get( + '/api/logs/events', + ({ query }) => { + const clauses = []; + const params = []; + + const type = query.get('type'); + if (type) { + clauses.push('type LIKE ?'); + params.push(`${type}%`); + } + const actorId = query.get('actorId'); + if (actorId) { + clauses.push('actor_id = ?'); + params.push(actorId); + } + const limit = Math.min(Number.parseInt(query.get('limit') ?? '100', 10), 500); + params.push(limit); + + const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : ''; + const events = getDatabase() + .prepare(`SELECT * FROM event_logs ${where} ORDER BY id DESC LIMIT ?`) + .all(...params) + .map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null })); + + return { + events, + types: getDatabase() + .prepare( + 'SELECT type, COUNT(*) AS count FROM event_logs GROUP BY type ORDER BY count DESC LIMIT 40', + ) + .all(), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/logs/files', + async () => { + const entries = await readdir(env.logDir).catch(() => []); + const files = []; + + for (const name of entries.filter((entry) => LOG_FILE.test(entry))) { + const info = await stat(path.join(env.logDir, name)).catch(() => null); + if (info) files.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() }); + } + return { directory: env.logDir, files: files.sort((a, b) => b.name.localeCompare(a.name)) }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.get( + '/api/logs/files/:name', + async ({ params, query }) => { + // The name pattern is the only thing standing between this route and the + // rest of the filesystem, so it is strict on purpose. + if (!LOG_FILE.test(params.name)) throw badRequest('Nom de fichier de log invalide.'); + + const content = await readFile(path.join(env.logDir, params.name), 'utf8').catch(() => null); + if (content === null) throw notFound('Fichier de log introuvable.'); + + const lines = Math.min(Number.parseInt(query.get('lines') ?? '300', 10), 2000); + const level = query.get('level'); + const parsed = content + .split('\n') + .filter(Boolean) + .map((line) => { + try { + return JSON.parse(line); + } catch { + return { level: 'info', message: line }; + } + }) + .filter((entry) => !level || entry.level === level); + + // `maskSecrets` already ran at write time; it runs again in case the file + // predates a secret rotation. + return { name: params.name, entries: JSON.parse(maskSecrets(JSON.stringify(parsed.slice(-lines)))) }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/organization.js b/src/web/api/organization.js new file mode 100644 index 0000000..e78a8b8 --- /dev/null +++ b/src/web/api/organization.js @@ -0,0 +1,179 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { org } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { badRequest } from '../http.js'; + +/** Organization-wide management (M16-T04). */ + +const requireGitea = () => { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); +}; + +const toMember = (member) => ({ + id: member.id, + login: member.login ?? member.username, + fullName: member.full_name, + email: member.email, + avatar: member.avatar_url, + isAdmin: member.is_admin, + lastLogin: member.last_login, + createdAt: member.created, +}); + +export function registerOrganizationRoutes(router) { + router.get( + '/api/organization', + async () => { + requireGitea(); + const [details, members, teams, repositories] = await Promise.all([ + org.get(), + org.listMembers({ limit: 100 }).catch(() => []), + org.listTeams({ limit: 100 }).catch(() => []), + org.listRepos({ limit: 100 }).catch(() => []), + ]); + + return { + name: details.username ?? details.name, + fullName: details.full_name, + description: details.description, + website: details.website, + location: details.location, + email: details.email, + avatar: details.avatar_url, + visibility: details.visibility, + url: `${env.gitea.url}/${details.username ?? details.name}`, + members: members.map(toMember), + teams: teams.map((team) => ({ + id: team.id, + name: team.name, + description: team.description, + permission: team.permission, + includesAllRepositories: team.includes_all_repositories, + canCreateOrgRepo: team.can_create_org_repo, + units: team.units, + })), + repositories: repositories.map((repository) => ({ + id: repository.id, + fullName: repository.full_name, + name: repository.name, + description: repository.description, + private: repository.private, + archived: repository.archived, + fork: repository.fork, + template: repository.template, + defaultBranch: repository.default_branch, + stars: repository.stars_count, + forks: repository.forks_count, + watchers: repository.watchers_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + releases: repository.release_counter, + sizeKb: repository.size, + language: repository.language, + updatedAt: repository.updated_at, + createdAt: repository.created_at, + htmlUrl: repository.html_url, + hasIssues: repository.has_issues, + hasPullRequests: repository.has_pull_requests, + hasActions: repository.has_actions, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/organization', + async ({ body, actor }) => { + requireGitea(); + const payload = {}; + for (const field of ['full_name', 'description', 'website', 'location', 'visibility']) { + if (field in body) payload[field] = String(body[field] ?? ''); + } + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + await org.update(payload); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.organization.update', + actorId: actor.userId, + payload: { fields: Object.keys(payload) }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/organization/teams/:id/members', + async ({ params }) => { + requireGitea(); + const members = await org.listTeamMembers(Number.parseInt(params.id, 10)); + return { members: members.map(toMember) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/organization/labels', + async () => { + requireGitea(); + return { labels: await org.listLabels() }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/organization/hooks', + async () => { + requireGitea(); + const hooks = await org.listHooks().catch(() => []); + return { + hooks: hooks.map((hook) => ({ + id: hook.id, + type: hook.type, + active: hook.active, + events: hook.events, + url: hook.config?.url, + createdAt: hook.created_at, + })), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Creates a repository inside the organization (M16-T04). */ + router.post( + '/api/organization/repositories', + async ({ body, actor }) => { + requireGitea(); + const name = String(body.name ?? '').trim(); + if (!/^[\w.-]{1,100}$/.test(name)) { + throw badRequest('Nom de dépôt invalide : lettres, chiffres, `.`, `-` et `_` uniquement.'); + } + + const created = await org.createRepo({ + name, + description: String(body.description ?? ''), + private: Boolean(body.private), + auto_init: body.autoInit !== false, + default_branch: String(body.defaultBranch ?? 'main'), + gitignores: body.gitignores ?? undefined, + license: body.license ?? undefined, + readme: body.readme ?? undefined, + issue_labels: body.issueLabels ?? undefined, + }); + + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.repository.create', + actorId: actor.userId, + payload: { repository: created.full_name }, + }); + return { fullName: created.full_name, htmlUrl: created.html_url }; + }, + { access: ACCESS_LEVELS.DEV }, + ); +} diff --git a/src/web/api/overview.js b/src/web/api/overview.js new file mode 100644 index 0000000..a079516 --- /dev/null +++ b/src/web/api/overview.js @@ -0,0 +1,158 @@ +import { version as discordJsVersion } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { getDatabase } from '../../database/index.js'; +import { + countByStatus, + lastDeploymentPerEnvironment, +} from '../../database/repositories/deploy-repository.js'; +import { countByAction } from '../../database/repositories/moderation-repository.js'; +import { countPolls } from '../../database/repositories/poll-repository.js'; +import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; +import { countVoiceChannels } from '../../database/repositories/voice-repository.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { org } from '../../services/gitea/gitea-admin.js'; + +/** Aggregated landing page of the dashboard (M16-T05). */ + +const guildId = () => env.discord.guildId; + +function botSnapshot(client, startedAt) { + const guild = client?.guilds?.cache?.get(guildId()) ?? null; + return { + online: Boolean(client?.isReady?.()), + username: client?.user?.username ?? null, + discriminator: client?.user?.discriminator ?? null, + avatar: client?.user?.displayAvatarURL?.({ size: 128 }) ?? null, + ping: client?.ws?.ping ?? null, + uptimeMs: Date.now() - startedAt, + nodeVersion: process.version, + discordJsVersion, + memoryMb: Math.round(process.memoryUsage().rss / 1024 / 1024), + commands: client?.commands?.size ?? 0, + guild: guild + ? { + id: guild.id, + name: guild.name, + icon: guild.iconURL?.({ size: 128 }) ?? null, + memberCount: guild.memberCount, + channelCount: guild.channels.cache.size, + roleCount: guild.roles.cache.size, + boostTier: guild.premiumTier, + createdAt: guild.createdAt?.toISOString() ?? null, + } + : null, + }; +} + +function databaseSnapshot() { + const database = getDatabase(); + const tables = database + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name") + .all() + .map((row) => row.name); + + const counts = Object.fromEntries( + tables.map((table) => [table, database.prepare(`SELECT COUNT(*) AS count FROM "${table}"`).get().count]), + ); + const pageCount = database.prepare('PRAGMA page_count').get(); + const pageSize = database.prepare('PRAGMA page_size').get(); + + return { + path: env.database.path, + tables: counts, + sizeBytes: (pageCount?.page_count ?? 0) * (pageSize?.page_size ?? 0), + migrations: database.prepare('SELECT name, applied_at FROM schema_migrations ORDER BY name').all(), + }; +} + +async function giteaSnapshot() { + if (!isGiteaConfigured()) return { configured: false }; + + const [organization, repositories] = await Promise.all([ + org.get().catch(() => null), + org.listRepos({ limit: 50 }).catch(() => []), + ]); + + const totals = repositories.reduce( + (accumulator, repository) => ({ + openIssues: accumulator.openIssues + (repository.open_issues_count ?? 0), + openPulls: accumulator.openPulls + (repository.open_pr_counter ?? 0), + stars: accumulator.stars + (repository.stars_count ?? 0), + forks: accumulator.forks + (repository.forks_count ?? 0), + sizeKb: accumulator.sizeKb + (repository.size ?? 0), + }), + { openIssues: 0, openPulls: 0, stars: 0, forks: 0, sizeKb: 0 }, + ); + + return { + configured: true, + url: env.gitea.url, + organization: organization && { + name: organization.username ?? organization.name, + fullName: organization.full_name, + description: organization.description, + website: organization.website, + location: organization.location, + avatar: organization.avatar_url, + visibility: organization.visibility, + }, + repositoryCount: repositories.length, + ...totals, + repositories: repositories + .slice() + .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at)) + .slice(0, 6) + .map((repository) => ({ + fullName: repository.full_name, + description: repository.description, + private: repository.private, + archived: repository.archived, + stars: repository.stars_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + updatedAt: repository.updated_at, + htmlUrl: repository.html_url, + })), + }; +} + +function recentEvents(limit = 15) { + return getDatabase() + .prepare('SELECT id, type, actor_id, payload, created_at FROM event_logs ORDER BY id DESC LIMIT ?') + .all(limit) + .map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null })); +} + +export function registerOverviewRoutes(router) { + router.get( + '/api/overview', + async ({ context }) => { + const id = guildId(); + const gitea = await giteaSnapshot(); + + return { + bot: botSnapshot(context.client, context.startedAt), + gitea, + database: databaseSnapshot(), + activity: { + openTickets: id ? countOpenTickets(id) : 0, + polls: id ? countPolls(id) : 0, + voiceChannels: id ? countVoiceChannels(id) : 0, + moderation: id ? countByAction(id) : [], + deployments: id ? countByStatus(id) : [], + environments: id ? lastDeploymentPerEnvironment(id) : [], + }, + events: recentEvents(), + features: { + webhooks: env.webhook.enabled, + commandDeploys: env.web.allowCommandDeploys, + restart: env.web.allowRestart, + gitea: isGiteaConfigured(), + }, + links: env.links, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/releases.js b/src/web/api/releases.js new file mode 100644 index 0000000..2666680 --- /dev/null +++ b/src/web/api/releases.js @@ -0,0 +1,260 @@ +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { repos } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { notify } from '../../services/notifications/notification-service.js'; +import { badRequest } from '../http.js'; +import { runAutoDeployments } from '../services/deploy-service.js'; + +/** Release management, the publishing half of the SaaS pipeline (M16-T08). */ + +const log = createLogger('web:releases'); +const NAME = /^[\w.-]{1,100}$/; + +function target(params) { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); + const { owner, repo } = params; + if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.'); + return { owner, repo, fullName: `${owner}/${repo}` }; +} + +const summarize = (release) => ({ + id: release.id, + tag: release.tag_name, + name: release.name, + body: release.body, + draft: release.draft, + prerelease: release.prerelease, + target: release.target_commitish, + author: release.author?.login, + createdAt: release.created_at, + publishedAt: release.published_at, + htmlUrl: release.html_url, + assets: (release.assets ?? []).map((asset) => ({ + id: asset.id, + name: asset.name, + size: asset.size, + downloads: asset.download_count, + url: asset.browser_download_url, + })), +}); + +/** Same grouping as `scripts/generate-changelog.js`, applied to Gitea commits. */ +const SECTIONS = [ + { title: 'Nouveautés', test: (type) => type === 'feat' }, + { title: 'Corrections', test: (type) => type === 'fix' }, + { title: 'Performance', test: (type) => type === 'perf' }, + { title: 'Autres changements', test: (type) => !['feat', 'fix', 'perf'].includes(type) }, +]; + +const CONVENTIONAL = /^(?[a-z]+)(?:\((?[^)]*)\))?(?!)?: (?.+)$/; + +/** + * Builds release notes from the commits that follow the previous tag. + * Commits that do not follow Conventional Commits are kept verbatim, so nothing + * silently disappears from the notes. + */ +export function buildReleaseNotes(commits, { previousTag = null } = {}) { + const parsed = commits.map((commit) => { + const subject = (commit.commit?.message ?? '').split('\n')[0].trim(); + const match = CONVENTIONAL.exec(subject); + return { + subject, + sha: commit.sha?.slice(0, 8), + type: match?.groups.type ?? 'other', + scope: match?.groups.scope ?? null, + description: match?.groups.description ?? subject, + breaking: Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(commit.commit?.message ?? ''), + }; + }); + + const lines = []; + const breaking = parsed.filter((commit) => commit.breaking); + if (breaking.length > 0) { + lines.push('### ⚠ Changements incompatibles', ''); + for (const commit of breaking) lines.push(`- ${commit.description} (${commit.sha})`); + lines.push(''); + } + + for (const section of SECTIONS) { + const entries = parsed.filter((commit) => section.test(commit.type)); + if (entries.length === 0) continue; + lines.push(`### ${section.title}`, ''); + for (const commit of entries) { + const scope = commit.scope ? `**${commit.scope}** : ` : ''; + lines.push(`- ${scope}${commit.description} (${commit.sha})`); + } + lines.push(''); + } + + if (previousTag) lines.push(`_Changements depuis \`${previousTag}\`._`); + return lines.join('\n').trim() || '_Aucun changement détecté._'; +} + +export function registerReleaseRoutes(router) { + router.get( + '/api/repositories/:owner/:repo/releases', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listReleases(owner, repo, { + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + }); + return { releases: list.map(summarize) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo/tags', + async ({ params }) => { + const { owner, repo } = target(params); + const tags = await repos.listTags(owner, repo, { limit: 50 }).catch(() => []); + return { + tags: tags.map((tag) => ({ + name: tag.name, + sha: tag.commit?.sha?.slice(0, 8), + url: tag.zipball_url, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** Proposes release notes before the release is actually created. */ + router.post( + '/api/repositories/:owner/:repo/releases/notes', + async ({ params, body }) => { + const { owner, repo } = target(params); + const branch = String(body.target ?? '') || undefined; + const [commits, releases] = await Promise.all([ + repos.listCommits(owner, repo, { sha: branch, limit: 50 }), + repos.listReleases(owner, repo, { limit: 1 }).catch(() => []), + ]); + + const previous = releases[0] ?? null; + // Gitea has no "compare since tag" endpoint on every version, so the cut is + // made on the published date of the previous release. + const since = previous?.published_at ? new Date(previous.published_at) : null; + const selected = since + ? commits.filter((commit) => new Date(commit.commit?.author?.date ?? 0) > since) + : commits; + + return { + previousTag: previous?.tag_name ?? null, + commitCount: selected.length, + notes: buildReleaseNotes(selected, { previousTag: previous?.tag_name ?? null }), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/releases', + async ({ params, body, actor, context }) => { + const { owner, repo, fullName } = target(params); + const tagName = String(body.tag ?? '').trim(); + if (!/^[\w.\-+/]{1,64}$/.test(tagName)) throw badRequest('Nom de tag invalide.'); + + const release = await repos.createRelease(owner, repo, { + tagName, + target: body.target ? String(body.target) : undefined, + name: String(body.name ?? tagName), + body: String(body.body ?? ''), + draft: Boolean(body.draft), + prerelease: Boolean(body.prerelease), + }); + + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.create', + actorId: actor.userId, + payload: { repository: fullName, tag: tagName, draft: Boolean(body.draft) }, + }); + + // A draft is not public yet: no announcement, no deployment. + let deployments = []; + if (!release.draft) { + await announceRelease(context.client, fullName, release).catch((error) => + log.warn('Could not announce the release', error), + ); + if (body.deploy !== false) { + deployments = await runAutoDeployments(context.client, { + repository: fullName, + releaseTag: release.tag_name, + ref: release.target_commitish, + triggeredBy: actor.userId, + }); + } + } + + return { release: summarize(release), deployments }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/repositories/:owner/:repo/releases/:id', + async ({ params, body, actor, context }) => { + const { owner, repo, fullName } = target(params); + const id = Number.parseInt(params.id, 10); + + const before = await repos.getRelease(owner, repo, id); + const payload = {}; + if ('name' in body) payload.name = String(body.name); + if ('body' in body) payload.body = String(body.body); + if ('draft' in body) payload.draft = Boolean(body.draft); + if ('prerelease' in body) payload.prerelease = Boolean(body.prerelease); + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + const release = await repos.updateRelease(owner, repo, id, payload); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.update', + actorId: actor.userId, + payload: { repository: fullName, tag: release.tag_name }, + }); + + // Publishing a draft is the moment the release becomes real. + if (before.draft && !release.draft) { + await announceRelease(context.client, fullName, release).catch(() => null); + } + return summarize(release); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/repositories/:owner/:repo/releases/:id', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeRelease(owner, repo, Number.parseInt(params.id, 10)); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.release.delete', + actorId: actor.userId, + payload: { repository: fullName, id: params.id }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); +} + +function announceRelease(client, fullName, release) { + if (!client) return Promise.resolve(null); + + return notify(client, 'release', { + embeds: [ + { + title: `${release.name || release.tag_name} — ${fullName}`, + url: release.html_url, + color: release.prerelease ? COLORS.warning : COLORS.gitea, + description: String(release.body ?? '').slice(0, 1800) || 'Nouvelle version publiée.', + footer: { text: release.prerelease ? 'Préversion' : 'Version stable' }, + timestamp: release.published_at ?? new Date().toISOString(), + }, + ], + }); +} diff --git a/src/web/api/repositories.js b/src/web/api/repositories.js new file mode 100644 index 0000000..3497db9 --- /dev/null +++ b/src/web/api/repositories.js @@ -0,0 +1,541 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { org, repos } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured } from '../../services/gitea/gitea-client.js'; +import { badRequest } from '../http.js'; + +/** Per-repository management (M16-T04). */ + +const NAME = /^[\w.-]{1,100}$/; + +function target(params) { + if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).'); + const { owner, repo } = params; + if (!NAME.test(owner ?? '') || !NAME.test(repo ?? '')) throw badRequest('Dépôt invalide.'); + return { owner, repo, fullName: `${owner}/${repo}` }; +} + +const number = (value, field) => { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed) || parsed < 0) throw badRequest(`Valeur numérique attendue pour ${field}.`); + return parsed; +}; + +const audit = (actor, type, payload) => + logEvent({ guildId: env.discord.guildId || null, type, actorId: actor.userId, payload }); + +const summarizeIssue = (issue) => ({ + number: issue.number, + title: issue.title, + state: issue.state, + body: issue.body, + labels: (issue.labels ?? []).map((label) => ({ name: label.name, color: label.color })), + assignees: (issue.assignees ?? []).map((user) => user.login), + author: issue.user?.login, + authorAvatar: issue.user?.avatar_url, + comments: issue.comments, + createdAt: issue.created_at, + updatedAt: issue.updated_at, + closedAt: issue.closed_at, + milestone: issue.milestone?.title ?? null, + htmlUrl: issue.html_url, +}); + +const summarizePull = (pull) => ({ + ...summarizeIssue(pull), + draft: pull.draft, + mergeable: pull.mergeable, + merged: pull.merged, + mergedAt: pull.merged_at, + head: pull.head?.ref, + base: pull.base?.ref, + additions: pull.additions, + deletions: pull.deletions, + changedFiles: pull.changed_files, +}); + +export function registerRepositoryRoutes(router) { + router.get( + '/api/repositories', + async () => { + if (!isGiteaConfigured()) return { configured: false, repositories: [] }; + const list = await org.listRepos({ limit: 100 }); + return { + configured: true, + repositories: list.map((repository) => ({ + fullName: repository.full_name, + name: repository.name, + owner: repository.owner?.login, + description: repository.description, + private: repository.private, + archived: repository.archived, + defaultBranch: repository.default_branch, + language: repository.language, + stars: repository.stars_count, + forks: repository.forks_count, + openIssues: repository.open_issues_count, + openPulls: repository.open_pr_counter, + releases: repository.release_counter, + sizeKb: repository.size, + updatedAt: repository.updated_at, + htmlUrl: repository.html_url, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo', + async ({ params }) => { + const { owner, repo } = target(params); + const [details, branches, languages, topics, collaborators, release] = await Promise.all([ + repos.get(owner, repo), + repos.listBranches(owner, repo, { limit: 100 }).catch(() => []), + repos.languages(owner, repo).catch(() => ({})), + repos.listTopics(owner, repo).catch(() => ({ topics: [] })), + repos.listCollaborators(owner, repo).catch(() => []), + repos.latestRelease(owner, repo).catch(() => null), + ]); + + return { + fullName: details.full_name, + name: details.name, + owner: details.owner?.login, + description: details.description, + website: details.website, + private: details.private, + archived: details.archived, + template: details.template, + fork: details.fork, + mirror: details.mirror, + empty: details.empty, + defaultBranch: details.default_branch, + defaultMergeStyle: details.default_merge_style, + allowMergeCommits: details.allow_merge_commits, + allowRebase: details.allow_rebase, + allowSquash: details.allow_squash_merge, + hasIssues: details.has_issues, + hasPullRequests: details.has_pull_requests, + hasWiki: details.has_wiki, + hasActions: details.has_actions, + hasReleases: details.has_releases, + stars: details.stars_count, + forks: details.forks_count, + watchers: details.watchers_count, + openIssues: details.open_issues_count, + openPulls: details.open_pr_counter, + releases: details.release_counter, + sizeKb: details.size, + createdAt: details.created_at, + updatedAt: details.updated_at, + htmlUrl: details.html_url, + cloneUrl: details.clone_url, + sshUrl: details.ssh_url, + permissions: details.permissions, + languages, + topics: topics.topics ?? [], + branches: branches.map((branch) => ({ + name: branch.name, + protected: branch.protected, + commit: branch.commit?.id?.slice(0, 8), + commitMessage: branch.commit?.message?.split('\n')[0], + commitAt: branch.commit?.timestamp, + })), + collaborators: collaborators.map((user) => ({ + login: user.login, + fullName: user.full_name, + avatar: user.avatar_url, + permissions: user.permissions, + })), + latestRelease: release && { + tag: release.tag_name, + name: release.name, + publishedAt: release.published_at, + htmlUrl: release.html_url, + }, + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/repositories/:owner/:repo', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const allowed = [ + 'description', + 'website', + 'private', + 'archived', + 'default_branch', + 'default_merge_style', + 'has_issues', + 'has_pull_requests', + 'has_wiki', + 'has_actions', + 'has_releases', + 'allow_merge_commits', + 'allow_rebase', + 'allow_squash_merge', + ]; + const payload = Object.fromEntries(Object.entries(body).filter(([key]) => allowed.includes(key))); + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + await repos.update(owner, repo, payload); + audit(actor, 'web.repository.update', { repository: fullName, fields: Object.keys(payload) }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** Deleting a repository is irreversible, so the full name must be typed back. */ + router.delete( + '/api/repositories/:owner/:repo', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + if (body.confirm !== fullName) { + throw badRequest(`Pour confirmer la suppression, renvoie exactement « ${fullName} ».`); + } + + await repos.remove(owner, repo); + audit(actor, 'web.repository.delete', { repository: fullName }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/repositories/:owner/:repo/topics', + async ({ params }) => { + const { owner, repo } = target(params); + return repos.listTopics(owner, repo); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/repositories/:owner/:repo/topics', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const topics = Array.isArray(body.topics) ? body.topics.map((topic) => String(topic).trim()) : null; + if (!topics) throw badRequest('`topics` doit être une liste.'); + + await repos.replaceTopics(owner, repo, topics); + audit(actor, 'web.repository.topics', { repository: fullName, topics }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Issues ---------------------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/issues', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listIssues(owner, repo, { + state: query.get('state') ?? 'open', + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + q: query.get('q') ?? undefined, + }); + return { issues: list.map(summarizeIssue) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/issues', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const title = String(body.title ?? '').trim(); + if (title.length < 3) throw badRequest('Le titre doit faire au moins 3 caractères.'); + + const issue = await repos.createIssue(owner, repo, { + title, + body: String(body.body ?? ''), + labels: body.labels ?? undefined, + assignees: body.assignees ?? undefined, + }); + audit(actor, 'web.issue.create', { repository: fullName, number: issue.number }); + return summarizeIssue(issue); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.patch( + '/api/repositories/:owner/:repo/issues/:number', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const issueNumber = number(params.number, 'number'); + + const payload = {}; + if ('state' in body) { + if (!['open', 'closed'].includes(body.state)) throw badRequest('État attendu : open ou closed.'); + payload.state = body.state; + } + for (const field of ['title', 'body', 'assignees', 'labels', 'milestone']) { + if (field in body) payload[field] = body[field]; + } + if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + const issue = await repos.updateIssue(owner, repo, issueNumber, payload); + audit(actor, 'web.issue.update', { + repository: fullName, + number: issueNumber, + fields: Object.keys(payload), + }); + return summarizeIssue(issue); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/issues/:number/comments', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const issueNumber = number(params.number, 'number'); + const message = String(body.body ?? '').trim(); + if (message === '') throw badRequest('Le commentaire est vide.'); + + const comment = await repos.commentIssue(owner, repo, issueNumber, message); + audit(actor, 'web.issue.comment', { repository: fullName, number: issueNumber }); + return { id: comment.id, htmlUrl: comment.html_url }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.get( + '/api/repositories/:owner/:repo/labels', + async ({ params }) => { + const { owner, repo } = target(params); + return { labels: await repos.listLabels(owner, repo) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + // --- Pull requests --------------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/pulls', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listPulls(owner, repo, { + state: query.get('state') ?? 'open', + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 50), + }); + return { pulls: list.map(summarizePull) }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/pulls', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const { title, head, base } = body; + if (!title || !head || !base) throw badRequest('`title`, `head` et `base` sont obligatoires.'); + + const pull = await repos.createPull(owner, repo, { + title: String(title), + body: String(body.body ?? ''), + head: String(head), + base: String(base), + }); + audit(actor, 'web.pull.create', { repository: fullName, number: pull.number }); + return summarizePull(pull); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.post( + '/api/repositories/:owner/:repo/pulls/:number/merge', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const pullNumber = number(params.number, 'number'); + const style = String(body.style ?? 'squash'); + if (!['merge', 'rebase', 'rebase-merge', 'squash'].includes(style)) { + throw badRequest('Méthode de merge inconnue.'); + } + + await repos.mergePull(owner, repo, pullNumber, { + style, + title: body.title ? String(body.title) : undefined, + message: body.message ? String(body.message) : undefined, + deleteBranch: Boolean(body.deleteBranch), + }); + audit(actor, 'web.pull.merge', { repository: fullName, number: pullNumber, style }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Branches and commits -------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/commits', + async ({ params, query }) => { + const { owner, repo } = target(params); + const list = await repos.listCommits(owner, repo, { + sha: query.get('branch') ?? undefined, + page: Number.parseInt(query.get('page') ?? '1', 10), + limit: Math.min(Number.parseInt(query.get('limit') ?? '25', 10), 50), + }); + return { + commits: list.map((commit) => ({ + sha: commit.sha, + shortSha: commit.sha?.slice(0, 8), + message: commit.commit?.message?.split('\n')[0], + author: commit.commit?.author?.name, + authorLogin: commit.author?.login, + avatar: commit.author?.avatar_url, + date: commit.commit?.author?.date, + htmlUrl: commit.html_url, + stats: commit.stats, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/repositories/:owner/:repo/branches', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const newBranchName = String(body.name ?? '').trim(); + if (newBranchName === '') throw badRequest('Nom de branche manquant.'); + + const branch = await repos.createBranch(owner, repo, { + newBranchName, + oldBranchName: body.from ? String(body.from) : undefined, + }); + audit(actor, 'web.branch.create', { repository: fullName, branch: newBranchName }); + return { name: branch.name }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/repositories/:owner/:repo/branches', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const branch = String(body.name ?? '').trim(); + if (branch === '') throw badRequest('Nom de branche manquant.'); + + await repos.removeBranch(owner, repo, branch); + audit(actor, 'web.branch.delete', { repository: fullName, branch }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Collaborators --------------------------------------------------------- + router.put( + '/api/repositories/:owner/:repo/collaborators/:username', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const permission = String(body.permission ?? 'write'); + if (!['read', 'write', 'admin'].includes(permission)) throw badRequest('Permission inconnue.'); + + await repos.addCollaborator(owner, repo, params.username, permission); + audit(actor, 'web.collaborator.add', { repository: fullName, user: params.username, permission }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/repositories/:owner/:repo/collaborators/:username', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeCollaborator(owner, repo, params.username); + audit(actor, 'web.collaborator.remove', { repository: fullName, user: params.username }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- Webhooks and actions -------------------------------------------------- + router.get( + '/api/repositories/:owner/:repo/hooks', + async ({ params }) => { + const { owner, repo } = target(params); + const hooks = await repos.listHooks(owner, repo).catch(() => []); + return { + hooks: hooks.map((hook) => ({ + id: hook.id, + type: hook.type, + active: hook.active, + events: hook.events, + url: hook.config?.url, + createdAt: hook.created_at, + })), + }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + /** + * Convenience route: wires Gitea to this bot's own webhook endpoint with the + * secret already configured, which is the step people most often get wrong. + */ + router.post( + '/api/repositories/:owner/:repo/hooks', + async ({ params, body, actor }) => { + const { owner, repo, fullName } = target(params); + const url = String(body.url ?? '').trim() || `${env.web.publicUrl}${env.webhook.path}`; + if (!url.startsWith('http')) throw badRequest('URL de webhook invalide.'); + + const secret = String(body.secret ?? '') || env.webhook.secret; + if (!secret) throw badRequest('Aucun secret disponible : renseigne `GITEA_WEBHOOK_SECRET`.'); + + const hook = await repos.createHook(owner, repo, { + url, + secret, + events: body.events ?? ['issues', 'pull_request', 'push', 'release'], + }); + audit(actor, 'web.hook.create', { repository: fullName, url }); + return { id: hook.id, url }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/repositories/:owner/:repo/hooks/:id', + async ({ params, actor }) => { + const { owner, repo, fullName } = target(params); + await repos.removeHook(owner, repo, number(params.id, 'id')); + audit(actor, 'web.hook.delete', { repository: fullName, hook: params.id }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.get( + '/api/repositories/:owner/:repo/actions', + async ({ params }) => { + const { owner, repo } = target(params); + // Gitea Actions is absent before 1.20 and returns 404 when disabled on the repo. + const payload = await repos.listActionTasks(owner, repo, { limit: 20 }).catch(() => null); + if (!payload) return { available: false, tasks: [] }; + + const tasks = Array.isArray(payload) ? payload : (payload.workflow_runs ?? payload.data ?? []); + return { + available: true, + tasks: tasks.map((task) => ({ + id: task.id, + name: task.name, + headBranch: task.head_branch, + headSha: task.head_sha?.slice(0, 8), + status: task.status, + conclusion: task.conclusion, + event: task.event, + runNumber: task.run_number, + createdAt: task.created_at, + updatedAt: task.updated_at, + })), + }; + }, + { access: ACCESS_LEVELS.STAFF }, + ); +} diff --git a/src/web/api/settings.js b/src/web/api/settings.js new file mode 100644 index 0000000..ae20c05 --- /dev/null +++ b/src/web/api/settings.js @@ -0,0 +1,366 @@ +import { randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import path from 'node:path'; +import { + ACCESS_LABELS, + ACCESS_LEVELS, + NOTIFICATION_TYPES, + TICKET_CATEGORIES, +} from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { getDatabase } from '../../database/index.js'; +import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js'; +import { getSetting, setSetting } from '../../database/repositories/settings-repository.js'; +import { + createApiToken, + deleteSession, + listApiTokens, + listSessions, + purgeExpiredSessions, + revokeApiToken, +} from '../../database/repositories/web-session-repository.js'; +import { org } from '../../services/gitea/gitea-admin.js'; +import { isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { badRequest, forbidden, notFound } from '../http.js'; +import { hashToken } from '../auth/session.js'; +import { isOauthConfigured, redirectUri } from '../auth/discord-oauth.js'; + +/** Everything the settings tab needs (M16-T10). */ + +const log = createLogger('web:settings'); +const guildId = () => env.discord.guildId; + +/** Guild settings the dashboard exposes as first-class switches. */ +const MANAGED_SETTINGS = Object.freeze([ + { + key: 'welcome.enabled', + label: 'Message de bienvenue', + help: 'Publier un message dans le salon d’accueil à chaque arrivée.', + type: 'bool', + default: true, + }, + { + key: 'welcome.directMessage', + label: 'Message privé de bienvenue', + help: 'Envoyer en plus un message privé au nouveau membre.', + type: 'bool', + default: false, + }, + { + key: 'departure.announce', + label: 'Annoncer les départs', + help: 'Publier une ligne dans les logs quand un membre quitte le serveur.', + type: 'bool', + default: true, + }, + { + key: 'moderation.dmTarget', + label: 'Prévenir le membre sanctionné', + help: 'Envoyer un message privé expliquant la sanction et son motif.', + type: 'bool', + default: true, + }, + { + key: 'tickets.autoClaim', + label: 'Prise en charge automatique', + help: 'Attribuer le ticket à la première personne du staff qui y écrit.', + type: 'bool', + default: false, + }, + { + key: 'deploy.requireConfirmation', + label: 'Confirmation avant déploiement', + help: 'Demander de retaper le nom de l’environnement avant de lancer un déploiement.', + type: 'bool', + default: true, + }, + { + key: 'web.defaultMode', + label: 'Mode d’affichage par défaut', + help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages).', + type: 'enum', + options: ['simple', 'advanced'], + default: 'simple', + }, +]); + +const readManaged = () => + Object.fromEntries( + MANAGED_SETTINGS.map((setting) => { + try { + return [setting.key, getSetting(guildId(), setting.key, setting.default)]; + } catch { + return [setting.key, setting.default]; + } + }), + ); + +export function registerSettingsRoutes(router) { + router.get( + '/api/settings', + ({ actor }) => ({ + schema: MANAGED_SETTINGS, + values: readManaged(), + runtime: { + nodeEnv: env.nodeEnv, + logLevel: env.logLevel, + logDir: env.logDir, + logRetentionDays: env.logRetentionDays, + databasePath: env.database.path, + backupDir: env.database.backupDir, + nodeVersion: process.version, + pid: process.pid, + }, + discord: { + clientId: env.discord.clientId, + guildId: env.discord.guildId, + roles: env.roles, + channels: env.channels, + tokenConfigured: Boolean(env.discord.token), + }, + gitea: { + configured: isGiteaConfigured(), + url: env.gitea.url, + owner: env.gitea.owner, + repo: env.gitea.repo, + repositoryUrl: repositoryUrl(), + timeoutMs: env.gitea.timeoutMs, + maxRetries: env.gitea.maxRetries, + tokenConfigured: Boolean(env.gitea.token), + }, + webhook: { + enabled: env.webhook.enabled, + host: env.webhook.host, + port: env.webhook.port, + path: env.webhook.path, + secretConfigured: Boolean(env.webhook.secret), + publicUrl: env.web.publicUrl ? `${env.web.publicUrl}${env.webhook.path}` : null, + }, + web: { + enabled: env.web.enabled, + host: env.web.host, + port: env.web.port, + publicUrl: env.web.publicUrl, + sessionTtlHours: env.web.sessionTtlHours, + oauthConfigured: isOauthConfigured(), + redirectUri: redirectUri(), + allowCommandDeploys: env.web.allowCommandDeploys, + allowRestart: env.web.allowRestart, + rateLimitPerMinute: env.web.rateLimitPerMinute, + }, + reference: { + notificationTypes: NOTIFICATION_TYPES, + ticketCategories: TICKET_CATEGORIES, + accessLevels: Object.entries(ACCESS_LEVELS).map(([name, value]) => ({ + name, + value, + label: ACCESS_LABELS[value], + })), + }, + viewer: { accessLevel: actor.accessLevel, accessLabel: ACCESS_LABELS[actor.accessLevel] }, + }), + { access: ACCESS_LEVELS.STAFF }, + ); + + router.put( + '/api/settings/values/:key', + ({ params, body, actor }) => { + const schema = MANAGED_SETTINGS.find((setting) => setting.key === params.key); + if (!schema) throw notFound('Réglage inconnu.'); + + let value = body.value; + if (schema.type === 'bool') value = Boolean(value); + else if (schema.type === 'enum') { + value = String(value); + if (!schema.options.includes(value)) + throw badRequest(`Valeurs possibles : ${schema.options.join(', ')}.`); + } + + setSetting(guildId(), schema.key, value, actor.userId); + logEvent({ + guildId: guildId(), + type: 'web.settings.update', + actorId: actor.userId, + payload: { key: schema.key, value }, + }); + return { key: schema.key, value }; + }, + { access: ACCESS_LEVELS.DEV }, + ); + + // --- Sessions -------------------------------------------------------------- + router.get( + '/api/settings/sessions', + ({ actor }) => ({ + sessions: listSessions().map((session) => ({ + ...session, + accessLabel: ACCESS_LABELS[session.access_level], + current: session.id === actor.sessionId, + })), + }), + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/settings/sessions/:id', + ({ params, actor }) => { + if (params.id === actor.sessionId) + throw badRequest('Utilise la déconnexion pour fermer ta propre session.'); + const removed = deleteSession(params.id); + if (removed === 0) throw notFound('Session introuvable.'); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- API tokens ------------------------------------------------------------ + router.get( + '/api/settings/tokens', + () => ({ + tokens: listApiTokens().map((token) => ({ + ...token, + accessLabel: ACCESS_LABELS[token.access_level], + active: !token.revoked_at, + })), + }), + { access: ACCESS_LEVELS.OWNER }, + ); + + /** The clear token is shown once and never stored, only its hash is kept. */ + router.post( + '/api/settings/tokens', + ({ body, actor }) => { + const name = String(body.name ?? '').trim(); + if (!/^[\w .-]{3,60}$/.test(name)) throw badRequest('Nom de jeton invalide (3 à 60 caractères).'); + + const accessLevel = Number.parseInt(body.accessLevel ?? ACCESS_LEVELS.STAFF, 10); + if (!Object.values(ACCESS_LEVELS).includes(accessLevel)) throw badRequest('Niveau d’accès inconnu.'); + if (accessLevel > actor.accessLevel) + throw forbidden('Tu ne peux pas créer un jeton plus puissant que toi.'); + + const token = `fws_${randomBytes(24).toString('base64url')}`; + const id = createApiToken({ + name, + tokenHash: hashToken(token), + prefix: token.slice(0, 12), + accessLevel, + createdBy: actor.userId, + expiresAt: body.expiresAt ? String(body.expiresAt) : null, + }); + + logEvent({ + guildId: guildId(), + type: 'web.token.create', + actorId: actor.userId, + payload: { id, name, accessLevel }, + }); + return { id, name, accessLevel, token }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.delete( + '/api/settings/tokens/:id', + ({ params, actor }) => { + const revoked = revokeApiToken(Number.parseInt(params.id, 10)); + if (revoked === 0) throw notFound('Jeton introuvable ou déjà révoqué.'); + logEvent({ + guildId: guildId(), + type: 'web.token.revoke', + actorId: actor.userId, + payload: { id: params.id }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + // --- Maintenance ----------------------------------------------------------- + router.post( + '/api/settings/backup', + ({ actor }) => { + mkdirSync(env.database.backupDir, { recursive: true }); + const file = path.join( + env.database.backupDir, + `fws-bot-${new Date().toISOString().replace(/[:.]/g, '-')}.sqlite`, + ); + // `VACUUM INTO` produces a consistent copy even with the WAL journal active. + getDatabase().exec(`VACUUM INTO '${file.replaceAll("'", "''")}'`); + + logEvent({ guildId: guildId(), type: 'web.backup', actorId: actor.userId, payload: { file } }); + log.info('Database backup written', { file }); + return { file }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + router.post( + '/api/settings/purge', + ({ body, actor }) => { + const days = Number.parseInt(body.days ?? env.logRetentionDays, 10); + if (!Number.isInteger(days) || days < 1) throw badRequest('Nombre de jours invalide.'); + + const events = purgeEventsOlderThan(days); + const sessions = purgeExpiredSessions(); + logEvent({ + guildId: guildId(), + type: 'web.purge', + actorId: actor.userId, + payload: { days, events, sessions }, + }); + return { events, sessions }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + + /** Checks the credentials without revealing them. */ + router.post( + '/api/settings/test/:service', + async ({ params, context }) => { + if (params.service === 'discord') { + const client = context.client; + return { + ok: Boolean(client?.isReady?.()), + detail: client?.isReady?.() + ? `Connecté en tant que ${client.user.tag}, ping ${client.ws.ping} ms.` + : 'Le bot n’est pas connecté à Discord.', + }; + } + + if (params.service === 'gitea') { + if (!isGiteaConfigured()) return { ok: false, detail: 'GITEA_URL ou GITEA_TOKEN manquant.' }; + try { + const user = await org.whoami(); + const organization = await org.get().catch(() => null); + return { + ok: true, + detail: `Jeton valide pour « ${user.login} »${organization ? `, accès à l’organisation « ${organization.username ?? organization.name} »` : ', mais l’organisation est inaccessible'}.`, + }; + } catch (error) { + return { ok: false, detail: `Échec de l’appel Gitea : ${error.message}` }; + } + } + + throw notFound('Service inconnu.'); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + /** + * Stops the process so a supervisor restarts it. Without one, the bot simply + * stops, which is why the capability is disabled by default. + */ + router.post( + '/api/settings/restart', + ({ actor }) => { + if (!env.web.allowRestart) throw forbidden('Le redémarrage est désactivé (`WEB_ALLOW_RESTART`).'); + + logEvent({ guildId: guildId(), type: 'web.restart', actorId: actor.userId, payload: null }); + log.warn('Restart requested from the dashboard', { actor: actor.userId }); + setTimeout(() => process.exit(0), 500).unref(); + return { ok: true, message: 'Redémarrage dans un instant…' }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); +} From 06a9be0cba1f964465eed89bca9b68ee77121012 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:43 +0200 Subject: [PATCH 09/51] feat(web): serve the dashboard and its interface The front-end is plain JavaScript served as is: no build step to run before the bot starts, and no second toolchain to keep alive. A simple/advanced switch hides the technical panels without ever standing in for a permission. `npm run setup` starts the wizard alone, because the bot refuses to boot without a token and the `.env` has to be writable from somewhere. When the webhook and the dashboard share a port, a single HTTP server is started. Co-Authored-By: Claude Opus 5 (1M context) --- eslint.config.js | 5 + package.json | 1 + scripts/setup-server.js | 47 ++ src/index.js | 13 +- src/web/public/app.js | 301 +++++++++ src/web/public/core/api.js | 51 ++ src/web/public/core/dom.js | 122 ++++ src/web/public/core/ui.js | 227 +++++++ src/web/public/favicon.svg | 5 + src/web/public/index.html | 18 + src/web/public/styles.css | 934 ++++++++++++++++++++++++++ src/web/public/views/community.js | 382 +++++++++++ src/web/public/views/deployments.js | 348 ++++++++++ src/web/public/views/discord.js | 428 ++++++++++++ src/web/public/views/login.js | 74 ++ src/web/public/views/logs.js | 155 +++++ src/web/public/views/organization.js | 285 ++++++++ src/web/public/views/overview.js | 205 ++++++ src/web/public/views/releases.js | 276 ++++++++ src/web/public/views/repositories.js | 969 +++++++++++++++++++++++++++ src/web/public/views/settings.js | 476 +++++++++++++ src/web/public/views/setup.js | 394 +++++++++++ src/web/server.js | 136 ++++ 23 files changed, 5850 insertions(+), 2 deletions(-) create mode 100644 scripts/setup-server.js create mode 100644 src/web/public/app.js create mode 100644 src/web/public/core/api.js create mode 100644 src/web/public/core/dom.js create mode 100644 src/web/public/core/ui.js create mode 100644 src/web/public/favicon.svg create mode 100644 src/web/public/index.html create mode 100644 src/web/public/styles.css create mode 100644 src/web/public/views/community.js create mode 100644 src/web/public/views/deployments.js create mode 100644 src/web/public/views/discord.js create mode 100644 src/web/public/views/login.js create mode 100644 src/web/public/views/logs.js create mode 100644 src/web/public/views/organization.js create mode 100644 src/web/public/views/overview.js create mode 100644 src/web/public/views/releases.js create mode 100644 src/web/public/views/repositories.js create mode 100644 src/web/public/views/settings.js create mode 100644 src/web/public/views/setup.js create mode 100644 src/web/server.js diff --git a/eslint.config.js b/eslint.config.js index 04fcf2c..a331612 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,5 +17,10 @@ export default [ eqeqeq: ['error', 'always'], }, }, + { + // The dashboard front-end runs in the browser, not in Node (M16-T11). + files: ['src/web/public/**/*.js'], + languageOptions: { globals: globals.browser }, + }, prettier, ]; diff --git a/package.json b/package.json index 5c5eaa1..2219944 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "scripts": { "start": "node src/index.js", "dev": "node --watch src/index.js", + "setup": "node scripts/setup-server.js", "deploy:commands": "node scripts/deploy-commands.js", "db:init": "node scripts/init-database.js", "changelog": "node scripts/generate-changelog.js", diff --git a/scripts/setup-server.js b/scripts/setup-server.js new file mode 100644 index 0000000..d3efa57 --- /dev/null +++ b/scripts/setup-server.js @@ -0,0 +1,47 @@ +#!/usr/bin/env node +import { env } from '../src/config/env.js'; +import { logger } from '../src/core/logger.js'; +import { initDatabase } from '../src/database/index.js'; +import { startWebServer } from '../src/web/server.js'; +import { generateRuntimeSetupToken, hasSetupToken } from '../src/web/setup-state.js'; + +/** + * Starts the configuration wizard alone, without connecting to Discord (M16-T09). + * + * This is the entry point for a fresh clone: the bot itself refuses to start + * without `DISCORD_TOKEN`, so the `.env` has to be writable from somewhere else. + * + * Usage: npm run setup + */ + +// The wizard stores its session in SQLite, so the database must exist. +initDatabase(); + +const token = env.web.setupToken || generateRuntimeSetupToken(); +const url = + env.web.publicUrl || `http://${env.web.host === '0.0.0.0' ? 'localhost' : env.web.host}:${env.web.port}`; + +const server = startWebServer({ client: null, setupOnly: true }); + +logger.info('Configuration wizard started'); +console.log(` +┌──────────────────────────────────────────────────────────────────────┐ +│ Assistant de configuration FWS-Bot │ +└──────────────────────────────────────────────────────────────────────┘ + + Ouvre ${url}/#/setup + Jeton ${token} + ${env.web.setupToken ? 'Ce jeton vient de WEB_SETUP_TOKEN.' : 'Ce jeton est temporaire : il change à chaque lancement.'} + + Une fois le .env enregistré : Ctrl+C, puis npm run db:init, + npm run deploy:commands et npm run dev. +`); + +if (!hasSetupToken()) logger.warn('No setup token available, the wizard cannot be opened'); + +const shutdown = () => { + server.close(); + process.exit(0); +}; +process.once('SIGINT', shutdown); +process.once('SIGTERM', shutdown); diff --git a/src/index.js b/src/index.js index 548fbf2..0a2f1f8 100644 --- a/src/index.js +++ b/src/index.js @@ -4,9 +4,15 @@ import { loadCommands } from './core/command-loader.js'; import { registerEvents } from './core/event-loader.js'; import { logger } from './core/logger.js'; import { closeDatabase, initDatabase } from './database/index.js'; +import { startWebServer, webhookSharesWebPort } from './web/server.js'; import { startWebhookServer } from './webhooks/server.js'; -assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); +try { + assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); +} catch (error) { + logger.error(`${error.message}. Lance \`npm run setup\` pour remplir le .env pas à pas.`); + throw error; +} initDatabase(); @@ -17,7 +23,9 @@ for (const command of await loadCommands()) { } await registerEvents(client); -const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null; +// When both listen on the same port, the dashboard serves the webhook route too. +const webServer = env.web.enabled ? startWebServer({ client }) : null; +const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null; process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason)); process.on('uncaughtException', (error) => logger.error('Uncaught exception', error)); @@ -25,6 +33,7 @@ process.on('uncaughtException', (error) => logger.error('Uncaught exception', er async function shutdown(signal) { logger.info(`Received ${signal}, shutting down`); webhookServer?.close(); + webServer?.close(); await client.destroy(); closeDatabase(); process.exit(0); diff --git a/src/web/public/app.js b/src/web/public/app.js new file mode 100644 index 0000000..41b81bc --- /dev/null +++ b/src/web/public/app.js @@ -0,0 +1,301 @@ +import { api } from './core/api.js'; +import { h, mount, qs } from './core/dom.js'; +import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js'; + +/** Shell, navigation and hash routing of the dashboard (M16-T11). */ + +const LEVELS = { USER: 0, STAFF: 1, DEV: 2, OWNER: 3 }; + +/** + * `module` is imported on demand, so a view is only downloaded when visited. + * `level` hides a page the visitor could not use anyway; the server enforces it too. + */ +const ROUTES = [ + { + path: '', + icon: '◎', + label: 'Vue d’ensemble', + group: 'Pilotage', + module: './views/overview.js', + level: LEVELS.STAFF, + }, + { + path: 'org', + icon: '⬡', + label: 'Organisation', + group: 'Pilotage', + module: './views/organization.js', + level: LEVELS.STAFF, + }, + { + path: 'repos', + icon: '◫', + label: 'Dépôts', + group: 'Code', + module: './views/repositories.js', + level: LEVELS.STAFF, + }, + { + path: 'releases', + icon: '⬀', + label: 'Releases', + group: 'Code', + module: './views/releases.js', + level: LEVELS.STAFF, + }, + { + path: 'deploy', + icon: '⚙', + label: 'Déploiements', + group: 'Code', + module: './views/deployments.js', + level: LEVELS.STAFF, + }, + { + path: 'discord', + icon: '☰', + label: 'Serveur Discord', + group: 'Communauté', + module: './views/discord.js', + level: LEVELS.STAFF, + }, + { + path: 'community', + icon: '✦', + label: 'Tickets & vocaux', + group: 'Communauté', + module: './views/community.js', + level: LEVELS.STAFF, + }, + { + path: 'logs', + icon: '≡', + label: 'Journaux', + group: 'Système', + module: './views/logs.js', + level: LEVELS.STAFF, + advanced: true, + }, + { + path: 'settings', + icon: '⚒', + label: 'Paramètres', + group: 'Système', + module: './views/settings.js', + level: LEVELS.STAFF, + }, + { + path: 'setup', + icon: '✎', + label: 'Configuration .env', + group: 'Système', + module: './views/setup.js', + level: LEVELS.OWNER, + }, +]; + +export const state = { + me: null, + config: null, + mode: localStorage.getItem('fws.mode') ?? 'simple', + theme: localStorage.getItem('fws.theme') ?? 'dark', + /** Repository selected in the Releases and Deployments pages. */ + repository: localStorage.getItem('fws.repository') ?? '', +}; + +export function setMode(mode) { + state.mode = mode; + localStorage.setItem('fws.mode', mode); + document.body.dataset.mode = mode; + render(); +} + +export function setTheme(theme) { + state.theme = theme; + localStorage.setItem('fws.theme', theme); + document.documentElement.dataset.theme = theme; +} + +export function setRepository(fullName) { + state.repository = fullName; + localStorage.setItem('fws.repository', fullName); +} + +export const navigate = (path) => { + window.location.hash = `#/${path}`; +}; + +const currentRoute = () => { + const raw = window.location.hash.replace(/^#\/?/, ''); + const [path] = raw.split('?'); + const segments = path.split('/').filter(Boolean); + return { segments, path }; +}; + +function sidebar() { + const { segments } = currentRoute(); + const active = segments[0] ?? ''; + const visible = ROUTES.filter( + (route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'), + ); + + const groups = []; + for (const route of visible) { + let group = groups.find((entry) => entry.name === route.group); + if (!group) groups.push((group = { name: route.group, routes: [] })); + group.routes.push(route); + } + + return h( + 'aside', + { class: 'sidebar' }, + h( + 'a', + { class: 'brand', href: '#/' }, + h('img', { src: 'favicon.svg', alt: '' }), + h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })), + ), + h( + 'nav', + { class: 'nav' }, + groups.map((group) => [ + h('div', { class: 'nav-group', text: group.name }), + group.routes.map((route) => + h( + 'a', + { href: `#/${route.path}`, class: route.path === active ? 'active' : '' }, + h('span', { class: 'nav-icon', text: route.icon }), + h('span', { text: route.label }), + ), + ), + ]), + ), + h( + 'div', + { class: 'sidebar-foot' }, + h( + 'div', + { class: 'mode-switch', role: 'group', 'aria-label': 'Mode d’affichage' }, + button('Simple', () => setMode('simple'), {}), + button('Avancé', () => setMode('advanced'), {}), + ), + h( + 'div', + { class: 'viewer' }, + state.me.avatar && h('img', { src: state.me.avatar, alt: '' }), + h( + 'div', + {}, + h('strong', { text: state.me.displayName ?? state.me.username ?? 'Invité' }), + h('span', { class: 'muted', text: ACCESS_LABELS[state.me.accessLevel] ?? '—' }), + ), + ), + h( + 'div', + { class: 'row' }, + button( + state.theme === 'dark' ? '☀ Clair' : '☾ Sombre', + () => { + setTheme(state.theme === 'dark' ? 'light' : 'dark'); + render(); + }, + { tone: 'ghost' }, + ), + button( + 'Déconnexion', + async () => { + await api.post('/api/auth/logout'); + window.location.reload(); + }, + { tone: 'ghost' }, + ), + ), + ), + ); +} + +function applyModeButtons(node) { + for (const control of node.querySelectorAll('.mode-switch button')) { + control.classList.toggle( + 'active', + control.textContent === (state.mode === 'simple' ? 'Simple' : 'Avancé'), + ); + } +} + +async function renderView(host) { + const { segments } = currentRoute(); + const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); + + if (!route) { + mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' }))); + return; + } + if (state.me.accessLevel < route.level) { + mount( + host, + h( + 'div', + { class: 'notice notice-error' }, + h('p', { text: 'Cette page demande un niveau d’accès supérieur.' }), + ), + ); + return; + } + + mount(host, spinner()); + try { + const module = await import(route.module); + await module.render(host, { params: segments.slice(1), state }); + } catch (error) { + mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message }))); + } +} + +export function render() { + const app = qs('#app'); + + if (!state.me?.authenticated) { + import('./views/login.js').then((module) => module.render(app, { state })); + return; + } + + // The bootstrap session may only reach the wizard, so it never gets a shell. + if (state.me.source === 'setup') { + import('./views/setup.js').then((module) => module.render(app, { state, standalone: true })); + return; + } + + const main = h('main', { class: 'main' }); + const shell = h('div', { class: 'shell' }, sidebar(), main); + mount(app, shell); + applyModeButtons(shell); + renderView(main); +} + +async function boot() { + document.body.dataset.mode = state.mode; + document.documentElement.dataset.theme = state.theme; + + const [me, config] = await Promise.all([ + api.get('/api/me').catch(() => ({ authenticated: false })), + api.get('/api/auth/config').catch(() => ({})), + ]); + state.me = me; + state.config = config; + + window.addEventListener('hashchange', () => { + if (state.me?.authenticated && state.me.source !== 'setup') renderView(qs('.main')); + else render(); + }); + window.addEventListener('unhandledrejection', (event) => { + if (event.reason?.status === 401) { + state.me = { authenticated: false }; + render(); + } else if (event.reason instanceof Error) toast(event.reason.message, 'error'); + }); + + render(); +} + +boot(); diff --git a/src/web/public/core/api.js b/src/web/public/core/api.js new file mode 100644 index 0000000..481bce0 --- /dev/null +++ b/src/web/public/core/api.js @@ -0,0 +1,51 @@ +/** Typed-ish client for the dashboard API (M16-T11). */ + +export class ApiError extends Error { + constructor(status, message, details) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.details = details; + } +} + +async function request(method, path, body) { + const response = await fetch(path, { + method, + headers: { + Accept: 'application/json', + ...(body !== undefined && { 'Content-Type': 'application/json' }), + // Required by the server for every write: a cross-site form cannot set it. + 'X-Requested-With': 'fws-dashboard', + }, + body: body === undefined ? undefined : JSON.stringify(body), + credentials: 'same-origin', + }); + + const payload = await response.json().catch(() => null); + if (!response.ok) { + throw new ApiError(response.status, payload?.error ?? `Erreur ${response.status}`, payload?.details); + } + return payload; +} + +const withQuery = (path, params) => { + const search = new URLSearchParams( + Object.entries(params ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== ''), + ).toString(); + return search ? `${path}?${search}` : path; +}; + +export const api = { + get: (path, params) => request('GET', withQuery(path, params)), + post: (path, body = {}) => request('POST', path, body), + put: (path, body = {}) => request('PUT', path, body), + patch: (path, body = {}) => request('PATCH', path, body), + delete: (path, body = {}) => request('DELETE', path, body), +}; + +export const encodeRepo = (fullName) => + String(fullName) + .split('/') + .map((part) => encodeURIComponent(part)) + .join('/'); diff --git a/src/web/public/core/dom.js b/src/web/public/core/dom.js new file mode 100644 index 0000000..6da3287 --- /dev/null +++ b/src/web/public/core/dom.js @@ -0,0 +1,122 @@ +/** + * Minimal DOM helpers. No framework, no build step: the dashboard ships the + * files it serves (M16-T11). + */ + +/** + * `h('div', { class: 'card' }, h('h2', { text: 'Titre' }))` + * Text always goes through `textContent`, so API values can never inject markup. + */ +export function h(tag, props = {}, ...children) { + const node = document.createElement(tag); + + for (const [key, value] of Object.entries(props ?? {})) { + if (value === null || value === undefined || value === false) continue; + + if (key === 'text') node.textContent = String(value); + else if (key === 'class') node.className = value; + else if (key === 'dataset') Object.assign(node.dataset, value); + else if (key === 'style') Object.assign(node.style, value); + else if (key.startsWith('on') && typeof value === 'function') { + node.addEventListener(key.slice(2).toLowerCase(), value); + } else if (key === 'value' || key === 'checked' || key === 'disabled' || key === 'selected') { + node[key] = value; + } else node.setAttribute(key, value === true ? '' : String(value)); + } + + for (const child of children.flat(Infinity)) { + if (child === null || child === undefined || child === false) continue; + node.append(child instanceof Node ? child : document.createTextNode(String(child))); + } + return node; +} + +export const clear = (node) => { + while (node.firstChild) node.firstChild.remove(); + return node; +}; + +export const mount = (node, ...children) => { + clear(node); + node.append(...children.flat(Infinity).filter(Boolean)); + return node; +}; + +export const qs = (selector, scope = document) => scope.querySelector(selector); + +/** Escapes then applies the small subset of Markdown used by Gitea bodies. */ +export function markdown(text) { + const escaped = String(text ?? '') + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>'); + + return escaped + .replace(/```([\s\S]*?)```/g, (_, code) => `
${code.trim()}
`) + .replace(/`([^`\n]+)`/g, '$1') + .replace(/^### (.+)$/gm, '

$1

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

$1

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

$1

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

    '); +} + +/** Renders trusted Markdown built above; never call it with raw HTML. */ +export function richText(text, className = 'rich') { + const node = h('div', { class: className }); + node.innerHTML = markdown(text); + return node; +} + +export const formatDate = (value) => { + if (!value) return '—'; + const date = new Date(String(value).includes('T') ? value : `${value}Z`); + if (Number.isNaN(date.getTime())) return String(value); + return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' }); +}; + +export function formatRelative(value) { + if (!value) return '—'; + const date = new Date(String(value).includes('T') ? value : `${value}Z`); + if (Number.isNaN(date.getTime())) return String(value); + + const seconds = Math.round((date.getTime() - Date.now()) / 1000); + const units = [ + ['year', 31_536_000], + ['month', 2_592_000], + ['day', 86_400], + ['hour', 3600], + ['minute', 60], + ]; + const formatter = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' }); + + for (const [unit, size] of units) { + if (Math.abs(seconds) >= size) return formatter.format(Math.round(seconds / size), unit); + } + return formatter.format(seconds, 'second'); +} + +export const formatBytes = (bytes) => { + const value = Number(bytes) || 0; + const units = ['o', 'Ko', 'Mo', 'Go']; + let index = 0; + let result = value; + while (result >= 1024 && index < units.length - 1) { + result /= 1024; + index += 1; + } + return `${result.toFixed(index === 0 ? 0 : 1)} ${units[index]}`; +}; + +export const formatDuration = (ms) => { + const seconds = Math.floor(Number(ms) / 1000); + const days = Math.floor(seconds / 86_400); + const hours = Math.floor((seconds % 86_400) / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + if (days > 0) return `${days} j ${hours} h`; + if (hours > 0) return `${hours} h ${minutes} min`; + if (minutes > 0) return `${minutes} min`; + return `${seconds} s`; +}; diff --git a/src/web/public/core/ui.js b/src/web/public/core/ui.js new file mode 100644 index 0000000..b3fec71 --- /dev/null +++ b/src/web/public/core/ui.js @@ -0,0 +1,227 @@ +import { clear, h, mount } from './dom.js'; + +/** Shared widgets: cards, tables, badges, toasts, modals (M16-T11). */ + +export const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' }; + +export function card(title, { subtitle, actions, advanced = false } = {}, ...children) { + return h( + 'section', + { class: advanced ? 'card advanced-only' : 'card' }, + (title || actions) && + h( + 'header', + { class: 'card-head' }, + h( + 'div', + {}, + title && h('h2', { text: title }), + subtitle && h('p', { class: 'muted', text: subtitle }), + ), + actions && h('div', { class: 'card-actions' }, actions), + ), + h('div', { class: 'card-body' }, ...children), + ); +} + +export const stat = (label, value, { hint, tone = 'neutral' } = {}) => + h( + 'div', + { class: `stat stat-${tone}` }, + h('span', { class: 'stat-label', text: label }), + h('strong', { class: 'stat-value', text: value ?? '—' }), + hint && h('span', { class: 'stat-hint', text: hint }), + ); + +export const badge = (text, tone = 'neutral') => h('span', { class: `badge badge-${tone}`, text }); + +export const button = (label, onClick, { tone = 'ghost', disabled = false, title, type = 'button' } = {}) => + h('button', { class: `btn btn-${tone}`, onClick, disabled, title, type, text: label }); + +export function field(label, control, { help, error } = {}) { + return h( + 'label', + { class: error ? 'field field-error' : 'field' }, + h('span', { class: 'field-label', text: label }), + control, + help && h('span', { class: 'field-help', text: help }), + error && h('span', { class: 'field-error-text', text: error }), + ); +} + +export const input = (props = {}) => h('input', { class: 'input', ...props }); +export const textarea = (props = {}) => h('textarea', { class: 'input textarea', ...props }); + +export function select(options, props = {}) { + return h( + 'select', + { class: 'input', ...props }, + options.map((option) => + h('option', { + value: option.value, + text: option.label, + selected: option.value === props.value, + }), + ), + ); +} + +export function toggle(checked, onChange, label) { + return h( + 'label', + { class: 'toggle' }, + h('input', { type: 'checkbox', checked, onChange: (event) => onChange(event.target.checked) }), + h('span', { class: 'toggle-track' }), + label && h('span', { text: label }), + ); +} + +/** + * Renders a table. Each column is `{ key, label, render?, className? }`; + * `render` returns a Node or a string. + */ +export function table(columns, rows, { empty = 'Rien à afficher pour le moment.' } = {}) { + if (!rows || rows.length === 0) return h('p', { class: 'empty', text: empty }); + + return h( + 'div', + { class: 'table-wrap' }, + h( + 'table', + { class: 'table' }, + h( + 'thead', + {}, + h( + 'tr', + {}, + columns.map((column) => h('th', { class: column.className ?? '', text: column.label })), + ), + ), + h( + 'tbody', + {}, + rows.map((row) => + h( + 'tr', + {}, + columns.map((column) => { + const cell = h('td', { class: column.className ?? '' }); + const value = column.render ? column.render(row) : row[column.key]; + if (value instanceof Node) cell.append(value); + else cell.textContent = value === null || value === undefined ? '—' : String(value); + return cell; + }), + ), + ), + ), + ), + ); +} + +export const spinner = (label = 'Chargement…') => + h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label })); + +export const errorBox = (message, { retry } = {}) => + h( + 'div', + { class: 'notice notice-error' }, + h('p', { text: message }), + retry && button('Réessayer', retry, { tone: 'ghost' }), + ); + +export const notice = (message, tone = 'info') => + h('div', { class: `notice notice-${tone}` }, h('p', { text: message })); + +let toastHost; + +export function toast(message, tone = 'success') { + toastHost ??= document.body.appendChild(h('div', { class: 'toast-host' })); + const node = h('div', { class: `toast toast-${tone}`, text: message }); + toastHost.append(node); + setTimeout(() => node.classList.add('toast-out'), 3600); + setTimeout(() => node.remove(), 4200); +} + +/** Promise-based modal. Resolves with the value passed to `close`. */ +export function modal(title, buildBody, { confirmLabel = 'Confirmer', tone = 'primary' } = {}) { + return new Promise((resolve) => { + const overlay = h('div', { class: 'overlay' }); + const close = (value) => { + overlay.remove(); + document.removeEventListener('keydown', onKey); + resolve(value); + }; + const onKey = (event) => { + if (event.key === 'Escape') close(null); + }; + + const body = buildBody(close); + const footer = h( + 'footer', + { class: 'modal-foot' }, + button('Annuler', () => close(null), { tone: 'ghost' }), + button(confirmLabel, () => close(body.submit ? body.submit() : true), { tone }), + ); + + overlay.append( + h( + 'div', + { class: 'modal' }, + h('header', { class: 'modal-head' }, h('h2', { text: title })), + h('div', { class: 'modal-body' }, body.node ?? body), + footer, + ), + ); + overlay.addEventListener('click', (event) => { + if (event.target === overlay) close(null); + }); + document.addEventListener('keydown', onKey); + document.body.append(overlay); + + const firstInput = overlay.querySelector('input, textarea, select'); + firstInput?.focus(); + }); +} + +/** Confirmation that requires typing an exact phrase, for irreversible actions. */ +export function confirmDangerous(title, message, phrase) { + return modal( + title, + () => { + const control = input({ placeholder: phrase, autocomplete: 'off' }); + const node = h( + 'div', + {}, + h('p', { text: message }), + h('p', { class: 'muted', text: `Tape « ${phrase} » pour confirmer.` }), + control, + ); + return { node, submit: () => control.value.trim() === phrase }; + }, + { confirmLabel: 'Supprimer', tone: 'danger' }, + ); +} + +export const confirmAction = (title, message) => + modal(title, () => ({ node: h('p', { text: message }), submit: () => true })); + +/** + * Renders an async view into a host node, showing a loader then the result. + * Any thrown error becomes a retry box instead of a blank page. + */ +export async function renderAsync(host, load, build) { + mount(host, spinner()); + try { + const data = await load(); + mount(host, await build(data)); + } catch (error) { + mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build) })); + } + return host; +} + +export const section = (...children) => h('div', { class: 'stack' }, ...children); +export const row = (...children) => h('div', { class: 'row' }, ...children); +export const grid = (...children) => h('div', { class: 'grid' }, ...children); +export { clear, mount }; diff --git a/src/web/public/favicon.svg b/src/web/public/favicon.svg new file mode 100644 index 0000000..928aab8 --- /dev/null +++ b/src/web/public/favicon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/web/public/index.html b/src/web/public/index.html new file mode 100644 index 0000000..e98b2dc --- /dev/null +++ b/src/web/public/index.html @@ -0,0 +1,18 @@ + + + + + + + + FWS-Bot — Tableau de bord + + + + +
    + +
    + + + diff --git a/src/web/public/styles.css b/src/web/public/styles.css new file mode 100644 index 0000000..f75ba4b --- /dev/null +++ b/src/web/public/styles.css @@ -0,0 +1,934 @@ +/* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */ + +:root { + --blue: #1793d1; + --blue-soft: #8fd3ff; + --green: #2ecc71; + --amber: #f1c40f; + --red: #e74c3c; + --violet: #9b59b6; + --gitea: #609926; + + --bg: #0b1016; + --bg-elevated: #121a24; + --bg-sunken: #080d12; + --surface: #16202c; + --border: #23303f; + --text: #e6edf3; + --text-muted: #8da2b6; + --shadow: 0 10px 30px rgb(0 0 0 / 35%); + + --radius: 12px; + --radius-sm: 8px; + --sidebar: 250px; + --font: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif; + --mono: ui-monospace, 'JetBrains Mono', 'Fira Code', Menlo, Consolas, monospace; +} + +[data-theme='light'] { + --bg: #f4f7fa; + --bg-elevated: #ffffff; + --bg-sunken: #e8eef5; + --surface: #ffffff; + --border: #d5e0ea; + --text: #14212e; + --text-muted: #5b6e80; + --shadow: 0 8px 24px rgb(20 33 46 / 10%); +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + height: 100%; +} + +body { + background: var(--bg); + color: var(--text); + font-family: var(--font); + font-size: 15px; + line-height: 1.55; + -webkit-font-smoothing: antialiased; +} + +a { + color: var(--blue-soft); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +h1, +h2, +h3, +h4 { + margin: 0; + line-height: 1.25; + font-weight: 650; +} +h1 { + font-size: 1.5rem; +} +h2 { + font-size: 1.05rem; +} +h3 { + font-size: 0.95rem; +} + +p { + margin: 0 0 0.6rem; +} +p:last-child { + margin-bottom: 0; +} + +code, +pre { + font-family: var(--mono); + font-size: 0.85em; +} +code { + background: var(--bg-sunken); + border-radius: 4px; + padding: 0.1em 0.35em; +} +pre { + background: var(--bg-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.8rem; + overflow: auto; + max-height: 400px; +} +pre code { + background: none; + padding: 0; +} + +.muted { + color: var(--text-muted); + font-size: 0.88rem; +} + +/* --- Layout ------------------------------------------------------------- */ + +.app { + min-height: 100%; +} + +.shell { + display: grid; + grid-template-columns: var(--sidebar) 1fr; + min-height: 100vh; +} + +.sidebar { + background: var(--bg-elevated); + border-right: 1px solid var(--border); + padding: 1.1rem 0.9rem; + display: flex; + flex-direction: column; + gap: 1.2rem; + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; +} + +.brand { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0 0.4rem; +} +.brand img { + width: 34px; + height: 34px; + border-radius: 9px; +} +.brand strong { + display: block; + font-size: 0.98rem; +} +.brand span { + display: block; + color: var(--text-muted); + font-size: 0.75rem; +} + +.nav { + display: flex; + flex-direction: column; + gap: 0.15rem; +} +.nav-group { + margin-top: 0.7rem; + padding: 0 0.6rem 0.25rem; + font-size: 0.68rem; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--text-muted); +} +.nav a { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.65rem; + border-radius: var(--radius-sm); + color: var(--text); + font-size: 0.9rem; +} +.nav a:hover { + background: var(--surface); + text-decoration: none; +} +.nav a.active { + background: color-mix(in srgb, var(--blue) 18%, transparent); + color: var(--blue-soft); + font-weight: 600; +} +.nav-icon { + width: 1.15rem; + text-align: center; + opacity: 0.85; +} + +.sidebar-foot { + margin-top: auto; + display: flex; + flex-direction: column; + gap: 0.6rem; + font-size: 0.8rem; +} + +.viewer { + display: flex; + align-items: center; + gap: 0.55rem; + padding: 0.5rem; + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.viewer img { + width: 30px; + height: 30px; + border-radius: 50%; +} +.viewer div { + min-width: 0; +} +.viewer strong { + display: block; + font-size: 0.85rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.main { + padding: 1.4rem 1.8rem 3rem; + min-width: 0; +} + +.page-head { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1.2rem; +} + +.stack { + display: flex; + flex-direction: column; + gap: 1rem; +} +.row { + display: flex; + flex-wrap: wrap; + gap: 0.6rem; + align-items: center; +} +.grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); + gap: 0.9rem; +} + +/* --- Components ---------------------------------------------------------- */ + +.card { + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; +} +.card-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + padding: 0.85rem 1.1rem; + border-bottom: 1px solid var(--border); +} +.card-actions { + display: flex; + gap: 0.45rem; + flex-wrap: wrap; +} +.card-body { + padding: 1.1rem; + display: flex; + flex-direction: column; + gap: 0.9rem; +} + +.stat { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.75rem 0.9rem; + display: flex; + flex-direction: column; + gap: 0.1rem; +} +.stat-label { + font-size: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-muted); +} +.stat-value { + font-size: 1.45rem; + line-height: 1.2; +} +.stat-hint { + font-size: 0.78rem; + color: var(--text-muted); +} +.stat-success .stat-value { + color: var(--green); +} +.stat-warning .stat-value { + color: var(--amber); +} +.stat-danger .stat-value { + color: var(--red); +} +.stat-primary .stat-value { + color: var(--blue-soft); +} + +.badge { + display: inline-flex; + align-items: center; + gap: 0.3rem; + padding: 0.12rem 0.5rem; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 600; + border: 1px solid transparent; + white-space: nowrap; +} +.badge-neutral { + background: var(--surface); + color: var(--text-muted); + border-color: var(--border); +} +.badge-success { + background: color-mix(in srgb, var(--green) 18%, transparent); + color: var(--green); +} +.badge-warning { + background: color-mix(in srgb, var(--amber) 18%, transparent); + color: var(--amber); +} +.badge-danger { + background: color-mix(in srgb, var(--red) 18%, transparent); + color: var(--red); +} +.badge-info { + background: color-mix(in srgb, var(--blue) 20%, transparent); + color: var(--blue-soft); +} +.badge-gitea { + background: color-mix(in srgb, var(--gitea) 22%, transparent); + color: #a8d96a; +} + +.btn { + font: inherit; + font-size: 0.86rem; + font-weight: 600; + padding: 0.42rem 0.8rem; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + cursor: pointer; + transition: + background 0.12s ease, + border-color 0.12s ease; +} +.btn:hover:not(:disabled) { + border-color: var(--blue); +} +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.btn-primary { + background: var(--blue); + border-color: var(--blue); + color: #04121c; +} +.btn-primary:hover:not(:disabled) { + filter: brightness(1.1); +} +.btn-danger { + background: color-mix(in srgb, var(--red) 16%, transparent); + border-color: var(--red); + color: var(--red); +} +.btn-success { + background: color-mix(in srgb, var(--green) 16%, transparent); + border-color: var(--green); + color: var(--green); +} +.btn-ghost { + background: transparent; +} +.btn-sm { + padding: 0.25rem 0.55rem; + font-size: 0.78rem; +} + +.field { + display: flex; + flex-direction: column; + gap: 0.28rem; +} +.field-label { + font-size: 0.82rem; + font-weight: 600; +} +.field-help { + font-size: 0.79rem; + color: var(--text-muted); +} +.field-error-text { + font-size: 0.79rem; + color: var(--red); +} +.field-error .input { + border-color: var(--red); +} + +.input { + font: inherit; + font-size: 0.88rem; + width: 100%; + padding: 0.45rem 0.6rem; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--bg-sunken); + color: var(--text); +} +.input:focus { + outline: 2px solid color-mix(in srgb, var(--blue) 55%, transparent); + outline-offset: 1px; + border-color: var(--blue); +} +.textarea { + min-height: 7rem; + resize: vertical; + font-family: var(--mono); + font-size: 0.82rem; +} + +.toggle { + display: inline-flex; + align-items: center; + gap: 0.5rem; + cursor: pointer; + font-size: 0.86rem; +} +.toggle input { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} +.toggle-track { + width: 36px; + height: 20px; + border-radius: 999px; + background: var(--border); + position: relative; + transition: background 0.15s ease; + flex: none; +} +.toggle-track::after { + content: ''; + position: absolute; + top: 2px; + left: 2px; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--text); + transition: transform 0.15s ease; +} +.toggle input:checked + .toggle-track { + background: var(--blue); +} +.toggle input:checked + .toggle-track::after { + transform: translateX(16px); + background: #04121c; +} +.toggle input:focus-visible + .toggle-track { + outline: 2px solid var(--blue-soft); + outline-offset: 2px; +} + +.table-wrap { + overflow-x: auto; + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.table { + width: 100%; + border-collapse: collapse; + font-size: 0.86rem; +} +.table th, +.table td { + text-align: left; + padding: 0.5rem 0.7rem; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} +.table th { + background: var(--surface); + font-size: 0.76rem; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-muted); + white-space: nowrap; +} +.table tbody tr:last-child td { + border-bottom: none; +} +.table tbody tr:hover { + background: color-mix(in srgb, var(--blue) 6%, transparent); +} +.num { + text-align: right; + font-variant-numeric: tabular-nums; +} +.nowrap { + white-space: nowrap; +} + +.empty { + color: var(--text-muted); + font-size: 0.88rem; + padding: 1rem; + text-align: center; + border: 1px dashed var(--border); + border-radius: var(--radius-sm); +} + +.notice { + border-radius: var(--radius-sm); + padding: 0.7rem 0.9rem; + border: 1px solid var(--border); + background: var(--surface); + font-size: 0.88rem; + display: flex; + gap: 0.8rem; + align-items: center; + justify-content: space-between; +} +.notice-error { + border-color: var(--red); + background: color-mix(in srgb, var(--red) 10%, transparent); +} +.notice-warning { + border-color: var(--amber); + background: color-mix(in srgb, var(--amber) 10%, transparent); +} +.notice-success { + border-color: var(--green); + background: color-mix(in srgb, var(--green) 10%, transparent); +} +.notice-info { + border-color: var(--blue); + background: color-mix(in srgb, var(--blue) 10%, transparent); +} + +.loading { + display: flex; + align-items: center; + gap: 0.6rem; + color: var(--text-muted); + padding: 1.6rem; + justify-content: center; +} +.spinner { + width: 16px; + height: 16px; + border: 2px solid var(--border); + border-top-color: var(--blue); + border-radius: 50%; + animation: spin 0.7s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.toast-host { + position: fixed; + right: 1rem; + bottom: 1rem; + display: flex; + flex-direction: column; + gap: 0.5rem; + z-index: 60; +} +.toast { + padding: 0.6rem 0.9rem; + border-radius: var(--radius-sm); + background: var(--bg-elevated); + border: 1px solid var(--border); + box-shadow: var(--shadow); + font-size: 0.87rem; + max-width: 24rem; + animation: toast-in 0.18s ease; +} +.toast-success { + border-color: var(--green); +} +.toast-error { + border-color: var(--red); +} +.toast-info { + border-color: var(--blue); +} +.toast-out { + opacity: 0; + transition: opacity 0.5s ease; +} +@keyframes toast-in { + from { + transform: translateY(8px); + opacity: 0; + } +} + +.overlay { + position: fixed; + inset: 0; + background: rgb(4 8 12 / 62%); + display: grid; + place-items: center; + padding: 1rem; + z-index: 70; +} +.modal { + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + width: min(620px, 100%); + max-height: 88vh; + display: flex; + flex-direction: column; +} +.modal-head { + padding: 0.9rem 1.1rem; + border-bottom: 1px solid var(--border); +} +.modal-body { + padding: 1.1rem; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 0.8rem; +} +.modal-foot { + padding: 0.8rem 1.1rem; + border-top: 1px solid var(--border); + display: flex; + justify-content: flex-end; + gap: 0.5rem; +} + +.rich { + font-size: 0.88rem; +} +.rich h3, +.rich h4 { + margin: 0.7rem 0 0.3rem; +} +.rich ul { + margin: 0.3rem 0; + padding-left: 1.2rem; +} + +/* --- Simple / advanced mode ---------------------------------------------- */ + +body[data-mode='simple'] .advanced-only { + display: none !important; +} + +.mode-switch { + display: flex; + border: 1px solid var(--border); + border-radius: 999px; + overflow: hidden; + font-size: 0.78rem; +} +.mode-switch button { + font: inherit; + font-weight: 600; + border: none; + background: transparent; + color: var(--text-muted); + padding: 0.28rem 0.75rem; + cursor: pointer; +} +.mode-switch button.active { + background: var(--blue); + color: #04121c; +} + +/* --- Login and setup ------------------------------------------------------ */ + +.centered { + min-height: 100vh; + display: grid; + place-items: center; + padding: 1.5rem; +} +.panel { + width: min(520px, 100%); + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + padding: 1.8rem; + display: flex; + flex-direction: column; + gap: 1rem; + text-align: center; +} +.panel .field { + text-align: left; +} + +.wizard { + display: grid; + grid-template-columns: 240px 1fr; + gap: 1.2rem; + align-items: start; +} +.wizard-steps { + display: flex; + flex-direction: column; + gap: 0.2rem; + position: sticky; + top: 1rem; +} +.wizard-step { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.6rem; + border-radius: var(--radius-sm); + border: 1px solid transparent; + background: none; + color: var(--text); + font: inherit; + font-size: 0.86rem; + text-align: left; + cursor: pointer; + width: 100%; +} +.wizard-step:hover { + background: var(--surface); +} +.wizard-step.active { + background: color-mix(in srgb, var(--blue) 16%, transparent); + border-color: var(--blue); +} +.wizard-step .dot { + width: 22px; + height: 22px; + flex: none; + border-radius: 50%; + display: grid; + place-items: center; + font-size: 0.72rem; + font-weight: 700; + border: 1px solid var(--border); + background: var(--bg-sunken); +} +.wizard-step.done .dot { + background: var(--green); + border-color: var(--green); + color: #04121c; +} +.wizard-step.invalid .dot { + background: var(--red); + border-color: var(--red); + color: #fff; +} + +.steps-list { + margin: 0; + padding-left: 1.2rem; + font-size: 0.87rem; + color: var(--text-muted); +} +.steps-list li { + margin-bottom: 0.3rem; +} +.steps-list strong { + color: var(--text); +} + +.secret-row { + display: flex; + gap: 0.4rem; + align-items: center; +} +.secret-row .input { + flex: 1; +} + +.diff { + font-family: var(--mono); + font-size: 0.8rem; +} +.diff del { + color: var(--red); + text-decoration: line-through; +} +.diff ins { + color: var(--green); + text-decoration: none; +} + +.log-line { + font-family: var(--mono); + font-size: 0.78rem; + padding: 0.18rem 0.4rem; + border-left: 3px solid var(--border); + white-space: pre-wrap; + word-break: break-word; +} +.log-error { + border-left-color: var(--red); +} +.log-warn { + border-left-color: var(--amber); +} +.log-info { + border-left-color: var(--blue); +} +.log-debug { + border-left-color: var(--border); + opacity: 0.75; +} + +.bar { + height: 6px; + border-radius: 999px; + background: var(--bg-sunken); + overflow: hidden; +} +.bar > span { + display: block; + height: 100%; + background: var(--blue); +} + +.repo-list { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 0.8rem; +} +.repo-card { + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.85rem; + background: var(--surface); + display: flex; + flex-direction: column; + gap: 0.45rem; +} +.repo-card h3 a { + color: var(--text); +} +.repo-meta { + display: flex; + gap: 0.8rem; + flex-wrap: wrap; + font-size: 0.78rem; + color: var(--text-muted); +} + +.tabs { + display: flex; + gap: 0.3rem; + border-bottom: 1px solid var(--border); + overflow-x: auto; +} +.tabs button { + font: inherit; + font-size: 0.86rem; + font-weight: 600; + background: none; + border: none; + border-bottom: 2px solid transparent; + color: var(--text-muted); + padding: 0.5rem 0.75rem; + cursor: pointer; + white-space: nowrap; +} +.tabs button.active { + color: var(--blue-soft); + border-bottom-color: var(--blue); +} + +@media (max-width: 900px) { + .shell { + grid-template-columns: 1fr; + } + .sidebar { + position: static; + height: auto; + flex-direction: column; + } + .main { + padding: 1rem; + } + .wizard { + grid-template-columns: 1fr; + } + .wizard-steps { + position: static; + flex-direction: row; + overflow-x: auto; + } +} diff --git a/src/web/public/views/community.js b/src/web/public/views/community.js new file mode 100644 index 0000000..79cc128 --- /dev/null +++ b/src/web/public/views/community.js @@ -0,0 +1,382 @@ +import { api } from '../core/api.js'; +import { formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + table, + toast, +} from '../core/ui.js'; + +/** Tickets, polls, temporary voice channels and the bot presence rotation. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const STATUS_TYPES = [ + { value: 'playing', label: 'joue à' }, + { value: 'watching', label: 'regarde' }, + { value: 'listening', label: 'écoute' }, + { value: 'competing', label: 'participe à' }, + { value: 'streaming', label: 'en direct sur' }, +]; + +function ticketsCard(data, level, reload) { + const labels = Object.fromEntries(data.categories.map((category) => [category.id, category.label])); + + return card( + 'Tickets', + { subtitle: `${data.tickets.filter((ticket) => ticket.status === 'open').length} ticket(s) ouvert(s)` }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Catégorie', render: (ticket) => labels[ticket.category_id] ?? ticket.category_id }, + { label: 'Auteur', render: (ticket) => ticket.author_id }, + { + label: 'État', + render: (ticket) => + ticket.status === 'open' ? badge('Ouvert', 'success') : badge('Clôturé', 'neutral'), + }, + { + label: 'Prise en charge', + className: 'advanced-only', + render: (ticket) => ticket.claimed_by ?? '—', + }, + { label: 'Ouvert', className: 'nowrap', render: (ticket) => formatRelative(ticket.created_at) }, + { + label: '', + render: (ticket) => + level >= LEVELS.STAFF && + ticket.status === 'open' && + button( + 'Clôturer', + async () => { + const reason = input({ placeholder: 'Motif de clôture' }); + const confirmed = await modal( + `Clôturer le ticket #${ticket.id}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', { text: 'Le salon privé associé sera supprimé.' }), + field('Motif', reason), + ), + submit: () => true, + }), + { confirmLabel: 'Clôturer', tone: 'danger' }, + ); + if (!confirmed) return; + await api.post(`/api/community/tickets/${ticket.id}/close`, { reason: reason.value }); + toast('Ticket clôturé.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + data.tickets, + { empty: 'Aucun ticket.' }, + ), + ); +} + +function pollsCard(polls, level, reload) { + return card( + 'Sondages', + { subtitle: `${polls.filter((poll) => poll.status === 'open').length} sondage(s) en cours` }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Question', key: 'question' }, + { + label: 'Résultats', + render: (poll) => { + const counts = Object.fromEntries(poll.counts.map((row) => [row.choice_index, row.count])); + const total = poll.counts.reduce((sum, row) => sum + row.count, 0) || 1; + return h( + 'div', + { class: 'stack', style: { gap: '0.2rem' } }, + poll.choices.map((choice, index) => + h( + 'div', + {}, + h( + 'div', + { class: 'row', style: { justifyContent: 'space-between', fontSize: '0.8rem' } }, + h('span', { text: choice }), + h('span', { class: 'muted', text: `${counts[index] ?? 0}` }), + ), + h( + 'div', + { class: 'bar' }, + h('span', { style: { width: `${((counts[index] ?? 0) / total) * 100}%` } }), + ), + ), + ), + ); + }, + }, + { + label: 'État', + render: (poll) => (poll.status === 'open' ? badge('Ouvert', 'success') : badge('Clos', 'neutral')), + }, + { label: 'Fin', className: 'nowrap advanced-only', render: (poll) => formatRelative(poll.ends_at) }, + { + label: '', + render: (poll) => + level >= LEVELS.STAFF && + poll.status === 'open' && + button( + 'Clore', + async () => { + if (!(await confirmAction('Clore le sondage', poll.question))) return; + await api.post(`/api/community/polls/${poll.id}/close`); + toast('Sondage clos.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + polls, + { empty: 'Aucun sondage.' }, + ), + ); +} + +function voiceCard(voice, level, reload) { + return card( + 'Salons vocaux temporaires', + { subtitle: `${voice.channels.filter((channel) => channel.alive).length} salon(s) actif(s)` }, + h('h3', { text: 'Déclencheurs' }), + table( + [ + { label: 'Salon déclencheur', render: (trigger) => trigger.label || trigger.triggerId }, + { label: 'Modèle de nom', render: (trigger) => trigger.template ?? '—' }, + { label: 'Limite', className: 'num', render: (trigger) => trigger.userLimit || '∞' }, + { + label: 'Actif', + render: (trigger) => (trigger.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { label: 'Salons vivants', className: 'num', key: 'activeChannels' }, + { + label: '', + render: (trigger) => + level >= LEVELS.DEV && + button( + trigger.enabled ? 'Mettre en pause' : 'Réactiver', + async () => { + await api.post(`/api/community/voice/triggers/${trigger.triggerId}/toggle`, { + enabled: !trigger.enabled, + }); + toast('Déclencheur mis à jour.'); + reload(); + }, + { tone: 'ghost' }, + ), + }, + ], + voice.triggers, + { + empty: + 'Aucun déclencheur configuré. Utilise `/voice setup` sur Discord ou renseigne CHANNEL_VOICE_TRIGGER_ID.', + }, + ), + + h('h3', { text: 'Salons générés' }), + table( + [ + { label: 'Salon', key: 'name' }, + { label: 'Propriétaire', render: (channel) => channel.owner_id }, + { label: 'Occupants', className: 'num', key: 'members' }, + { + label: 'État', + render: (channel) => + h( + 'div', + { class: 'row' }, + channel.alive ? badge('Vivant', 'success') : badge('Fantôme', 'warning'), + channel.locked && badge('Verrouillé', 'info'), + ), + }, + { label: 'Créé', className: 'nowrap', render: (channel) => formatRelative(channel.created_at) }, + { + label: '', + render: (channel) => + level >= LEVELS.STAFF && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le salon', channel.name))) return; + await api.delete(`/api/community/voice/channels/${channel.channel_id}`); + toast('Salon supprimé.'); + reload(); + }, + { tone: 'danger' }, + ), + }, + ], + voice.channels, + { empty: 'Aucun salon temporaire pour l’instant.' }, + ), + ); +} + +function statusesCard(statuses, intervalSeconds, level, reload) { + const interval = input({ type: 'number', value: intervalSeconds, min: 5, style: { maxWidth: '8rem' } }); + + return card( + 'Présence du bot', + { + subtitle: 'Les statuts défilent dans l’ordre d’ajout.', + actions: + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + 'Ajouter un statut', + async () => { + const text = input({ placeholder: 'les issues de FWS Arch' }); + const type = select(STATUS_TYPES, { value: 'watching' }); + const url = input({ placeholder: 'https://twitch.tv/… (type « en direct » uniquement)' }); + + const confirmed = await modal( + 'Nouveau statut', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Type', type), + field('Texte', text), + field('Lien', url), + ), + submit: () => text.value.trim() !== '', + }), + { confirmLabel: 'Ajouter', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post('/api/community/statuses', { + text: text.value, + type: type.value, + url: url.value || undefined, + }); + toast('Statut ajouté.'); + reload(); + }, + { tone: 'primary' }, + ), + ), + }, + + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + field('Rythme de rotation (secondes)', interval), + button( + 'Enregistrer', + async () => { + const result = await api.put('/api/community/statuses/interval', { + seconds: Number(interval.value), + }); + toast(`Rotation réglée sur ${result.intervalSeconds} s. Effective au prochain redémarrage.`); + }, + { tone: 'ghost' }, + ), + ), + + table( + [ + { label: '#', className: 'num', key: 'id' }, + { + label: 'Statut', + render: (status) => { + const type = STATUS_TYPES.find((item) => item.value === status.type); + return `${type?.label ?? status.type} ${status.text}`; + }, + }, + { + label: 'Actif', + render: (status) => (status.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { + label: '', + render: (status) => + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + status.enabled ? 'Pause' : 'Activer', + async () => { + await api.patch(`/api/community/statuses/${status.id}`, { enabled: !status.enabled }); + toast('Statut mis à jour.'); + reload(); + }, + { tone: 'ghost' }, + ), + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le statut', status.text))) return; + await api.delete(`/api/community/statuses/${status.id}`); + toast('Statut supprimé.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ], + statuses, + { empty: 'Aucun statut : le bot affiche sa ligne par défaut.' }, + ), + ); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + return renderAsync( + host, + async () => { + const [tickets, polls, voice, statuses] = await Promise.all([ + api.get('/api/community/tickets', { limit: 100 }), + api.get('/api/community/polls', { limit: 30 }), + api.get('/api/community/voice'), + api.get('/api/community/statuses'), + ]); + return { tickets, polls: polls.polls, voice, statuses }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Tickets & vocaux' }), + h('p', { class: 'muted', text: 'Le quotidien de la communauté, géré depuis le site.' }), + ), + ), + data.voice.triggers.length === 0 && + notice('Aucun salon « rejoindre pour créer » : la fonctionnalité vocale reste inactive.', 'info'), + ticketsCard(data.tickets, level, reload), + pollsCard(data.polls, level, reload), + voiceCard(data.voice, level, reload), + statusesCard(data.statuses.statuses, data.statuses.intervalSeconds, level, reload), + ), + ); +} diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js new file mode 100644 index 0000000..ca7421b --- /dev/null +++ b/src/web/public/views/deployments.js @@ -0,0 +1,348 @@ +import { api } from '../core/api.js'; +import { formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + table, + toast, + toggle, +} from '../core/ui.js'; + +/** Deploy targets and deployment history — the operations side of the SaaS (M16-T06). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const STATUS_TONE = { + success: 'success', + failed: 'danger', + running: 'warning', + pending: 'neutral', + cancelled: 'neutral', +}; + +const KINDS = [ + { value: 'webhook', label: 'Webhook signé (recommandé)' }, + { value: 'gitea-action', label: 'Workflow Gitea Actions' }, + { value: 'command', label: 'Commande shell sur l’hôte du bot' }, +]; + +const KIND_HELP = { + webhook: + 'Le bot envoie une requête POST signée en HMAC-SHA256 à ton serveur. C’est la méthode la plus sûre : rien ne s’exécute sur la machine du bot.', + 'gitea-action': + 'Le bot déclenche un workflow Gitea Actions. Le workflow doit accepter `workflow_dispatch`.', + command: + 'Le bot exécute une commande shell sur sa propre machine. À réserver à des personnes de confiance : c’est une exécution de code arbitraire.', +}; + +async function editTarget(existing, repositories, commandsAllowed, level, reload) { + const name = input({ value: existing?.name ?? '', placeholder: 'production-web' }); + const repository = select( + repositories.map((item) => ({ value: item.fullName, label: item.fullName })), + { value: existing?.repository ?? repositories[0]?.fullName }, + ); + const environment = input({ value: existing?.environment ?? 'production' }); + const kindOptions = KINDS.filter( + (kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER), + ); + const kind = select(kindOptions, { value: existing?.kind ?? 'webhook' }); + + const url = input({ value: existing?.config?.url ?? '', placeholder: 'https://deploy.exemple.org/hook' }); + const secret = input({ + type: 'password', + placeholder: existing?.config?.hasSecret ? 'Inchangé' : 'Secret HMAC', + }); + const command = input({ + value: existing?.config?.command ?? '', + placeholder: 'systemctl restart fws-arch', + }); + const cwd = input({ + value: existing?.config?.cwd ?? '', + placeholder: 'Répertoire de travail (facultatif)', + }); + const workflow = input({ value: existing?.config?.workflow ?? '', placeholder: 'deploy.yml' }); + const ref = input({ value: existing?.config?.ref ?? '', placeholder: 'main' }); + + let autoDeploy = existing?.autoDeploy ?? false; + let enabled = existing?.enabled ?? true; + + const specific = h('div', { class: 'stack' }); + const help = h('p', { class: 'muted' }); + + const drawSpecific = () => { + help.textContent = KIND_HELP[kind.value]; + const fields = { + webhook: [ + field('URL', url), + field('Secret partagé', secret, { + help: 'Envoyé en en-tête `X-FWS-Signature` (HMAC-SHA256 du corps JSON).', + }), + ], + command: [field('Commande', command), field('Répertoire de travail', cwd)], + 'gitea-action': [ + field('Fichier de workflow', workflow, { help: 'Nom du fichier dans `.gitea/workflows/`.' }), + field('Référence', ref, { help: 'Branche ou tag sur lequel déclencher le workflow.' }), + ], + }; + mount(specific, fields[kind.value] ?? []); + }; + kind.addEventListener('change', drawSpecific); + drawSpecific(); + + const confirmed = await modal( + existing ? `Modifier « ${existing.name} »` : 'Nouvelle cible de déploiement', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom', name), + field('Dépôt', repository), + field('Environnement', environment, { help: 'production, staging, preview…' }), + field('Type', kind), + help, + specific, + toggle( + autoDeploy, + (checked) => (autoDeploy = checked), + 'Déployer automatiquement à chaque release publiée', + ), + toggle(enabled, (checked) => (enabled = checked), 'Cible active'), + ), + submit: () => name.value.trim() !== '', + }), + { confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const config = {}; + if (kind.value === 'webhook') { + config.url = url.value.trim(); + if (secret.value) config.secret = secret.value; + } else if (kind.value === 'command') { + config.command = command.value.trim(); + config.cwd = cwd.value.trim(); + } else { + config.workflow = workflow.value.trim(); + config.ref = ref.value.trim(); + } + + const payload = { + name: name.value.trim(), + repository: repository.value, + environment: environment.value.trim(), + kind: kind.value, + config, + autoDeploy, + enabled, + }; + + if (existing) await api.patch(`/api/deploy/targets/${existing.id}`, payload); + else await api.post('/api/deploy/targets', payload); + + toast(existing ? 'Cible mise à jour.' : 'Cible créée.'); + reload(); +} + +async function runTarget(target, requireConfirmation, reload) { + const releaseTag = input({ placeholder: 'v1.2.3 (facultatif)' }); + const ref = input({ placeholder: 'main (facultatif)' }); + + const confirmed = await modal( + `Déployer « ${target.name} »`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', {}, 'Environnement : ', h('strong', { text: target.environment })), + h('p', { class: 'muted', text: target.summary }), + field('Version à déployer', releaseTag), + field('Référence git', ref), + requireConfirmation && h('p', { class: 'muted', text: 'Le déploiement démarre dès la validation.' }), + ), + submit: () => true, + }), + { confirmLabel: 'Déployer', tone: 'primary' }, + ); + if (!confirmed) return; + + toast('Déploiement lancé…', 'info'); + const result = await api.post(`/api/deploy/targets/${target.id}/run`, { + releaseTag: releaseTag.value.trim() || undefined, + ref: ref.value.trim() || undefined, + }); + + toast( + result.status === 'success' + ? 'Déploiement réussi.' + : `Déploiement en échec : ${result.error ?? 'raison inconnue'}`, + result.status === 'success' ? 'success' : 'error', + ); + reload(); +} + +const showLog = (deployment) => + modal(`Déploiement #${deployment.id}`, () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', {}, h('strong', { text: deployment.target_name }), ` · ${deployment.environment}`), + h('p', { + class: 'muted', + text: `${deployment.repository} · ${deployment.release_tag ?? deployment.ref ?? '—'}`, + }), + deployment.error && h('p', { class: 'field-error-text', text: deployment.error }), + h('pre', {}, h('code', { text: deployment.log || 'Aucune sortie.' })), + ), + submit: () => true, + })); + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + return renderAsync( + host, + async () => { + const [targets, deployments, repositories] = await Promise.all([ + api.get('/api/deploy/targets'), + api.get('/api/deployments', { limit: 40 }), + api.get('/api/repositories'), + ]); + return { + ...targets, + deployments: deployments.deployments, + repositories: repositories.repositories ?? [], + }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Déploiements' }), + h('p', { + class: 'muted', + text: 'Déclare où livrer chaque dépôt, puis déploie à la demande ou automatiquement à chaque release.', + }), + ), + level >= LEVELS.DEV && + data.repositories.length > 0 && + button( + 'Nouvelle cible', + () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'primary' }, + ), + ), + + !data.commandDeploysAllowed && + notice( + 'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.', + 'info', + ), + + card( + 'Cibles', + { subtitle: `${data.targets.length} cible(s) configurée(s)` }, + table( + [ + { + label: 'Cible', + render: (target) => + h( + 'div', + {}, + h('strong', { text: target.name }), + h('div', { class: 'muted', text: target.summary }), + ), + }, + { label: 'Dépôt', key: 'repository' }, + { label: 'Environnement', render: (target) => badge(target.environment, 'info') }, + { + label: 'Type', + className: 'advanced-only', + render: (target) => badge(target.kind, target.kind === 'command' ? 'warning' : 'neutral'), + }, + { + label: 'Auto', + render: (target) => + target.autoDeploy ? badge('Auto', 'success') : badge('Manuel', 'neutral'), + }, + { + label: 'Actif', + render: (target) => (target.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')), + }, + { + label: '', + render: (target) => + h( + 'div', + { class: 'row' }, + level >= LEVELS.DEV && + button('Déployer', () => runTarget(target, true, reload), { + tone: 'primary', + disabled: !target.enabled, + }), + level >= LEVELS.DEV && + button( + 'Modifier', + () => + editTarget(target, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'ghost' }, + ), + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la cible', `Supprimer « ${target.name} » ?`))) + return; + await api.delete(`/api/deploy/targets/${target.id}`); + toast('Cible supprimée.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ], + data.targets, + { empty: 'Aucune cible pour l’instant. Crée-en une pour déployer depuis ce site.' }, + ), + ), + + card( + 'Historique', + { subtitle: 'Les 40 derniers déploiements, réussis comme échoués.' }, + table( + [ + { label: '#', className: 'num', key: 'id' }, + { label: 'Cible', key: 'target_name' }, + { label: 'Environnement', key: 'environment' }, + { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' }, + { + label: 'État', + render: (row) => badge(row.status, STATUS_TONE[row.status] ?? 'neutral'), + }, + { label: 'Source', className: 'advanced-only', key: 'source' }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) }, + { label: '', render: (row) => button('Journal', () => showLog(row), { tone: 'ghost' }) }, + ], + data.deployments, + { empty: 'Aucun déploiement enregistré.' }, + ), + ), + ), + ); +} diff --git a/src/web/public/views/discord.js b/src/web/public/views/discord.js new file mode 100644 index 0000000..97356b1 --- /dev/null +++ b/src/web/public/views/discord.js @@ -0,0 +1,428 @@ +import { api } from '../core/api.js'; +import { formatDate, formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + spinner, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Discord server console: members, roles, moderation, announcements, routing. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; +const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' }; +const ACCESS_TONE = { 0: 'neutral', 1: 'info', 2: 'success', 3: 'danger' }; + +const DURATIONS = [ + { value: String(5 * 60_000), label: '5 minutes' }, + { value: String(60 * 60_000), label: '1 heure' }, + { value: String(24 * 60 * 60_000), label: '1 jour' }, + { value: String(7 * 24 * 60 * 60_000), label: '7 jours' }, +]; + +const MODERATION_ACTIONS = [ + { value: 'warn', label: 'Avertissement' }, + { value: 'mute', label: 'Exclusion temporaire' }, + { value: 'kick', label: 'Expulsion' }, + { value: 'ban', label: 'Bannissement' }, +]; + +async function moderate(member, reload) { + const action = select(MODERATION_ACTIONS, { value: 'warn' }); + const reason = input({ placeholder: 'Motif communiqué au membre' }); + const duration = select(DURATIONS, { value: DURATIONS[1].value }); + const durationField = field('Durée', duration); + durationField.style.display = 'none'; + + action.addEventListener('change', () => { + durationField.style.display = action.value === 'mute' ? '' : 'none'; + }); + + const confirmed = await modal( + `Modérer ${member.displayName}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + notice( + 'Le barème de rôles s’applique : tu ne peux pas agir sur quelqu’un au moins aussi haut placé.', + 'info', + ), + field('Action', action), + field('Motif', reason), + durationField, + ), + submit: () => true, + }), + { confirmLabel: 'Appliquer', tone: 'danger' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/discord/moderation', { + action: action.value, + userId: member.id, + reason: reason.value, + durationMs: action.value === 'mute' ? Number(duration.value) : undefined, + }); + toast(`${result.label} appliqué.`); + reload(); +} + +async function manageRoles(member, roles, reload) { + const picker = select( + roles.filter((role) => !role.managed).map((role) => ({ value: role.id, label: role.name })), + {}, + ); + const current = h( + 'div', + { class: 'row' }, + member.roles.map((roleId) => { + const role = roles.find((item) => item.id === roleId); + return badge(role?.name ?? roleId, 'info'); + }), + ); + let mode = 'add'; + + const confirmed = await modal( + `Rôles de ${member.displayName}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('h3', { text: 'Rôles actuels' }), + member.roles.length > 0 ? current : h('p', { class: 'muted', text: 'Aucun rôle.' }), + field( + 'Action', + select( + [ + { value: 'add', label: 'Ajouter' }, + { value: 'remove', label: 'Retirer' }, + ], + { value: 'add', onChange: (event) => (mode = event.target.value) }, + ), + ), + field('Rôle', picker), + ), + submit: () => true, + }), + { confirmLabel: 'Appliquer' }, + ); + if (!confirmed) return; + + await api.post(`/api/discord/members/${member.id}/roles`, { roleId: picker.value, action: mode }); + toast('Rôles mis à jour.'); + reload(); +} + +async function announce(channels) { + const channel = select( + channels + .filter((item) => item.kind === 'text' || item.kind === 'announcement') + .map((item) => ({ value: item.id, label: `#${item.name}` })), + {}, + ); + const title = input({ placeholder: 'Titre (facultatif)' }); + const content = textarea({ placeholder: 'Ton message…' }); + let asEmbed = true; + + const confirmed = await modal( + 'Publier une annonce', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Salon', channel), + field('Titre', title), + field('Message', content), + toggle(true, (checked) => (asEmbed = checked), 'Publier sous forme d’embed'), + ), + submit: () => content.value.trim() !== '' || title.value.trim() !== '', + }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/discord/announce', { + channelId: channel.value, + title: title.value, + content: content.value, + asEmbed, + }); + toast(`Annonce publiée (${result.messageId}).`); +} + +function membersCard(guild, level) { + const host = h('div', { class: 'stack' }); + const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' }); + + const load = () => + renderAsync( + host, + () => api.get('/api/discord/members', { q: search.value.trim(), limit: 100 }), + (data) => + table( + [ + { + label: 'Membre', + render: (member) => + h( + 'div', + { class: 'row' }, + h('img', { + src: member.avatar, + alt: '', + width: 26, + height: 26, + style: { borderRadius: '50%' }, + }), + h( + 'div', + {}, + h('strong', { text: member.displayName }), + h('div', { class: 'muted', text: `@${member.username}` }), + ), + ), + }, + { + label: 'Niveau', + render: (member) => badge(ACCESS_LABELS[member.accessLevel], ACCESS_TONE[member.accessLevel]), + }, + { + label: 'Arrivé', + className: 'nowrap advanced-only', + render: (member) => formatRelative(member.joinedAt), + }, + { + label: 'État', + render: (member) => + member.timeoutUntil && new Date(member.timeoutUntil) > new Date() + ? badge('Exclu', 'warning') + : member.bot + ? badge('Bot', 'neutral') + : '—', + }, + { + label: '', + render: (member) => + h( + 'div', + { class: 'row' }, + level >= LEVELS.STAFF && button('Modérer', () => moderate(member, load), { tone: 'ghost' }), + level >= LEVELS.DEV && + button('Rôles', () => manageRoles(member, guild.roles, load), { tone: 'ghost' }), + ), + }, + ], + data.members, + { empty: 'Aucun membre ne correspond.' }, + ), + ); + + let timer = null; + search.addEventListener('input', () => { + clearTimeout(timer); + timer = setTimeout(load, 300); + }); + load(); + + return card('Membres', { subtitle: `${guild.memberCount} membre(s)`, actions: search }, host); +} + +function notificationsCard(guild, level) { + const host = h('div', { class: 'stack' }); + + const load = () => + renderAsync( + host, + () => api.get('/api/discord/notifications'), + (data) => { + const overrides = Object.fromEntries(data.overrides.map((row) => [row.type, row.channel_id])); + const channels = guild.channels.filter( + (item) => item.kind === 'text' || item.kind === 'announcement', + ); + + return table( + [ + { label: 'Type', key: 'type' }, + { + label: 'Salon par défaut (.env)', + className: 'advanced-only', + render: (row) => { + const channel = guild.channels.find((item) => item.id === row.fallback); + return channel ? `#${channel.name}` : '—'; + }, + }, + { + label: 'Salon utilisé', + render: (row) => { + if (level < LEVELS.STAFF) return row.current ? `#${row.current}` : '—'; + const picker = select( + [ + { value: '', label: 'Valeur par défaut du .env' }, + ...channels.map((item) => ({ value: item.id, label: `#${item.name}` })), + ], + { + value: overrides[row.type] ?? '', + onChange: async (event) => { + await api.put(`/api/discord/notifications/${row.type}`, { + channelId: event.target.value, + }); + toast('Routage mis à jour.'); + }, + }, + ); + return picker; + }, + }, + ], + Object.keys(data.defaults).map((type) => ({ + type, + fallback: data.defaults[type], + current: overrides[type] ?? data.defaults[type], + })), + ); + }, + ); + + load(); + return card( + 'Notifications', + { subtitle: 'Où le bot publie les événements Gitea et ses propres messages.' }, + host, + ); +} + +export async function render(host, { state }) { + const level = state.me.accessLevel; + mount(host, spinner()); + + let guild; + try { + guild = await api.get('/api/discord/guild'); + } catch (error) { + mount(host, notice(error.message, 'error')); + return; + } + + const byKind = (kind) => guild.channels.filter((channel) => channel.kind === kind).length; + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + { class: 'row' }, + guild.icon && + h('img', { src: guild.icon, alt: '', width: 48, height: 48, style: { borderRadius: '12px' } }), + h( + 'div', + {}, + h('h1', { text: guild.name }), + h('p', { class: 'muted', text: `Créé le ${formatDate(guild.createdAt)}` }), + ), + ), + level >= LEVELS.STAFF && + button('Publier une annonce', () => announce(guild.channels), { tone: 'primary' }), + ), + + card( + 'Serveur', + {}, + grid( + stat('Membres', guild.memberCount, { tone: 'primary' }), + stat('Salons texte', byKind('text')), + stat('Salons vocaux', byKind('voice')), + stat('Rôles', guild.roles.length), + stat('Boosts', guild.boostCount ?? 0), + stat('Niveau de boost', guild.boostTier), + ), + ), + + membersCard(guild, level), + + card( + 'Rôles', + { advanced: true, subtitle: 'Ordre hiérarchique, du plus élevé au plus bas.' }, + table( + [ + { + label: 'Rôle', + render: (role) => + h( + 'div', + { class: 'row' }, + h('span', { + style: { + width: '12px', + height: '12px', + borderRadius: '50%', + background: role.color === '#000000' ? 'var(--border)' : role.color, + display: 'inline-block', + }, + }), + h('span', { text: role.name }), + ), + }, + { label: 'Membres', className: 'num', key: 'memberCount' }, + { label: 'Position', className: 'num', key: 'position' }, + { + label: 'Rôle FWS', + render: (role) => { + const mapping = Object.entries(guild.mapping.roles).find(([, id]) => id === role.id); + return mapping ? badge(mapping[0], 'success') : '—'; + }, + }, + ], + guild.roles, + ), + ), + + notificationsCard(guild, level), + + card( + 'Commandes', + { advanced: true, subtitle: 'Commandes slash chargées et niveau requis.' }, + await renderCommands(), + ), + ), + ); +} + +async function renderCommands() { + const host = h('div', {}); + renderAsync( + host, + () => api.get('/api/discord/commands'), + (data) => + table( + [ + { label: 'Commande', render: (command) => `/${command.name}` }, + { label: 'Description', key: 'description' }, + { label: 'Niveau', render: (command) => badge(command.accessLabel, ACCESS_TONE[command.access]) }, + { + label: 'Sous-commandes', + render: (command) => (command.options ?? []).map((option) => option.name).join(', ') || '—', + }, + ], + data.commands, + ), + ); + return host; +} diff --git a/src/web/public/views/login.js b/src/web/public/views/login.js new file mode 100644 index 0000000..cdaa4e3 --- /dev/null +++ b/src/web/public/views/login.js @@ -0,0 +1,74 @@ +import { api } from '../core/api.js'; +import { h, mount } from '../core/dom.js'; +import { button, field, input, notice, toast } from '../core/ui.js'; + +/** Sign-in page: Discord OAuth2, or the bootstrap token when nothing is configured yet. */ + +const ERRORS = { + 'oauth-not-configured': + 'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET` et `WEB_PUBLIC_URL`, puis redémarre le bot.', + 'state-mismatch': 'La session de connexion a expiré. Réessaie.', + 'exchange-failed': + 'Discord a refusé l’échange du code. Vérifie l’URL de redirection déclarée dans le portail.', + 'not-a-member': 'Ton compte Discord n’est pas membre du serveur FWS.', + 'insufficient-level': 'Ton compte n’a pas le rôle Staff, Dev ou Owner sur le serveur.', + 'missing-code': 'Discord n’a pas renvoyé de code d’autorisation.', + access_denied: 'Connexion annulée.', +}; + +export function render(host, { state }) { + const params = new URLSearchParams(window.location.hash.split('?')[1] ?? ''); + const failure = params.get('error'); + const config = state.config ?? {}; + + const tokenInput = input({ type: 'password', placeholder: 'Jeton d’amorçage', autocomplete: 'off' }); + + const submitSetupToken = async () => { + try { + await api.post('/api/auth/setup', { token: tokenInput.value.trim() }); + window.location.hash = '#/setup'; + window.location.reload(); + } catch (error) { + toast(error.message, 'error'); + } + }; + + mount( + host, + h( + 'div', + { class: 'centered' }, + h( + 'div', + { class: 'panel' }, + h('img', { src: 'favicon.svg', alt: '', width: 56, height: 56, style: { margin: '0 auto' } }), + h('h1', { text: 'FWS-Bot' }), + h('p', { class: 'muted', text: 'Administration du bot, de l’organisation et des déploiements.' }), + + failure && notice(ERRORS[failure] ?? `Connexion refusée (${failure}).`, 'error'), + + config.oauthConfigured + ? h('a', { class: 'btn btn-primary', href: '/auth/login', text: 'Se connecter avec Discord' }) + : notice( + 'La connexion Discord n’est pas encore disponible. Utilise le jeton d’amorçage pour ouvrir l’assistant de configuration.', + 'warning', + ), + + config.setupAvailable && + h( + 'div', + { class: 'stack' }, + h('hr', { style: { border: 'none', borderTop: '1px solid var(--border)', width: '100%' } }), + field('Jeton d’amorçage', tokenInput, { + help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration.', + }), + button('Ouvrir l’assistant de configuration', submitSetupToken, { tone: 'ghost' }), + ), + ), + ), + ); + + tokenInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') submitSetupToken(); + }); +} diff --git a/src/web/public/views/logs.js b/src/web/public/views/logs.js new file mode 100644 index 0000000..901a4a5 --- /dev/null +++ b/src/web/public/views/logs.js @@ -0,0 +1,155 @@ +import { api } from '../core/api.js'; +import { formatBytes, formatDate, formatRelative, h, mount } from '../core/dom.js'; +import { badge, button, card, renderAsync, select, table, toast } from '../core/ui.js'; + +/** Functional event log and daily technical log files. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +function eventsCard() { + const host = h('div', { class: 'stack' }); + let typeFilter = ''; + + const load = () => + renderAsync( + host, + () => api.get('/api/logs/events', { type: typeFilter, limit: 150 }), + (data) => + h( + 'div', + { class: 'stack' }, + select( + [ + { value: '', label: 'Tous les événements' }, + ...data.types.map((row) => ({ value: row.type, label: `${row.type} (${row.count})` })), + ], + { + value: typeFilter, + onChange: (event) => { + typeFilter = event.target.value; + load(); + }, + }, + ), + table( + [ + { label: 'Type', render: (event) => badge(event.type, 'info') }, + { label: 'Auteur', render: (event) => event.actor_id ?? '—' }, + { + label: 'Détail', + render: (event) => (event.payload ? JSON.stringify(event.payload) : '—'), + }, + { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) }, + ], + data.events, + { empty: 'Aucun événement enregistré.' }, + ), + ), + ); + + load(); + return card('Événements fonctionnels', { subtitle: 'Ce que le bot a fait, et pour qui.' }, host); +} + +function filesCard() { + const host = h('div', { class: 'stack' }); + const viewer = h('div', { class: 'stack' }); + let levelFilter = ''; + + const openFile = (name) => + renderAsync( + viewer, + () => api.get(`/api/logs/files/${name}`, { lines: 400, level: levelFilter }), + (data) => + card( + data.name, + { + actions: select( + [ + { value: '', label: 'Tous les niveaux' }, + { value: 'debug', label: 'debug' }, + { value: 'info', label: 'info' }, + { value: 'warn', label: 'warn' }, + { value: 'error', label: 'error' }, + ], + { + value: levelFilter, + onChange: (event) => { + levelFilter = event.target.value; + openFile(name); + }, + }, + ), + }, + h( + 'div', + { class: 'stack', style: { gap: '0.1rem', maxHeight: '28rem', overflowY: 'auto' } }, + data.entries.length === 0 + ? h('p', { class: 'empty', text: 'Aucune ligne pour ce filtre.' }) + : data.entries.map((entry) => + h('div', { + class: `log-line log-${entry.level ?? 'info'}`, + text: `${entry.time ? formatDate(entry.time) : ''} [${entry.scope ?? '—'}] ${entry.message ?? ''}${ + entry.meta ? ` ${JSON.stringify(entry.meta)}` : '' + }`, + }), + ), + ), + ), + ); + + renderAsync( + host, + () => api.get('/api/logs/files'), + (data) => + table( + [ + { label: 'Fichier', key: 'name' }, + { label: 'Taille', className: 'num', render: (file) => formatBytes(file.sizeBytes) }, + { label: 'Modifié', className: 'nowrap', render: (file) => formatRelative(file.modifiedAt) }, + { label: '', render: (file) => button('Ouvrir', () => openFile(file.name), { tone: 'ghost' }) }, + ], + data.files, + { empty: 'Aucun fichier de log.' }, + ), + ); + + return h( + 'div', + { class: 'stack' }, + card('Journaux techniques', { subtitle: 'Un fichier JSON par jour, secrets masqués.' }, host), + viewer, + ); +} + +export function render(host, { state }) { + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Journaux' }), + h('p', { class: 'muted', text: 'Ce que le bot a fait et ce qu’il a rencontré.' }), + ), + state.me.accessLevel >= LEVELS.OWNER && + button( + 'Purger les anciens événements', + async () => { + const result = await api.post('/api/settings/purge', {}); + toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`); + render(host, { state }); + }, + { tone: 'ghost' }, + ), + ), + eventsCard(), + state.me.accessLevel >= LEVELS.DEV ? filesCard() : null, + ), + ); +} diff --git a/src/web/public/views/organization.js b/src/web/public/views/organization.js new file mode 100644 index 0000000..3ca94d0 --- /dev/null +++ b/src/web/public/views/organization.js @@ -0,0 +1,285 @@ +import { api } from '../core/api.js'; +import { formatBytes, formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + field, + grid, + input, + modal, + renderAsync, + select, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Organization page: identity, members, teams and repository inventory. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +async function editOrganization(data, refresh) { + const fullName = input({ value: data.fullName ?? '' }); + const description = textarea({ value: data.description ?? '' }); + const website = input({ value: data.website ?? '', placeholder: 'https://…' }); + const location = input({ value: data.location ?? '' }); + const visibility = select( + [ + { value: 'public', label: 'Publique' }, + { value: 'limited', label: 'Limitée aux comptes connectés' }, + { value: 'private', label: 'Privée' }, + ], + { value: data.visibility ?? 'public' }, + ); + + const confirmed = await modal( + 'Modifier l’organisation', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom affiché', fullName), + field('Description', description), + field('Site web', website), + field('Localisation', location), + field('Visibilité', visibility), + ), + submit: () => true, + }), + { confirmLabel: 'Enregistrer' }, + ); + if (!confirmed) return; + + await api.patch('/api/organization', { + full_name: fullName.value, + description: description.value, + website: website.value, + location: location.value, + visibility: visibility.value, + }); + toast('Organisation mise à jour.'); + refresh(); +} + +async function createRepository(refresh) { + const name = input({ placeholder: 'mon-nouveau-depot' }); + const description = input({ placeholder: 'À quoi sert ce dépôt ?' }); + const defaultBranch = input({ value: 'main' }); + let isPrivate = false; + let autoInit = true; + + const confirmed = await modal( + 'Créer un dépôt', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Nom', name, { help: 'Lettres, chiffres, points, tirets et soulignés.' }), + field('Description', description), + field('Branche par défaut', defaultBranch), + toggle(false, (checked) => (isPrivate = checked), 'Dépôt privé'), + toggle(true, (checked) => (autoInit = checked), 'Initialiser avec un README'), + ), + submit: () => name.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const created = await api.post('/api/organization/repositories', { + name: name.value.trim(), + description: description.value, + defaultBranch: defaultBranch.value, + private: isPrivate, + autoInit, + }); + toast(`Dépôt ${created.fullName} créé.`); + refresh(); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const refresh = () => render(host, { state }); + + return renderAsync( + host, + () => api.get('/api/organization'), + (data) => { + const totals = data.repositories.reduce( + (accumulator, repository) => ({ + issues: accumulator.issues + (repository.openIssues ?? 0), + pulls: accumulator.pulls + (repository.openPulls ?? 0), + size: accumulator.size + (repository.sizeKb ?? 0) * 1024, + }), + { issues: 0, pulls: 0, size: 0 }, + ); + + return h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: data.fullName || data.name }), + h('p', { class: 'muted', text: data.description || 'Organisation Gitea de FWS.' }), + ), + h( + 'div', + { class: 'row' }, + h('a', { + class: 'btn btn-ghost', + href: data.url, + target: '_blank', + rel: 'noreferrer', + text: '↗ Voir sur Gitea', + }), + level >= LEVELS.DEV && + button('Nouveau dépôt', () => createRepository(refresh), { tone: 'primary' }), + level >= LEVELS.OWNER && + button('Modifier', () => editOrganization(data, refresh), { tone: 'ghost' }), + ), + ), + + card( + 'Chiffres clés', + {}, + grid( + stat('Dépôts', data.repositories.length, { tone: 'primary' }), + stat('Membres', data.members.length), + stat('Équipes', data.teams.length), + stat('Issues ouvertes', totals.issues, { tone: totals.issues > 0 ? 'warning' : 'neutral' }), + stat('PR ouvertes', totals.pulls), + stat('Taille totale', formatBytes(totals.size)), + ), + ), + + card( + 'Dépôts', + { subtitle: 'Clique sur un dépôt pour le gérer en détail.' }, + table( + [ + { + label: 'Dépôt', + render: (repository) => + h( + 'div', + {}, + h('a', { href: `#/repos/${repository.fullName}`, text: repository.name }), + repository.description && h('div', { class: 'muted', text: repository.description }), + ), + }, + { + label: 'État', + render: (repository) => + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + repository.fork && badge('Fork', 'info'), + ), + }, + { + label: 'Langage', + render: (repository) => repository.language || '—', + className: 'advanced-only', + }, + { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 }, + { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 }, + { + label: 'Releases', + className: 'num advanced-only', + render: (repository) => repository.releases ?? 0, + }, + { + label: 'Mise à jour', + className: 'nowrap', + render: (repository) => formatRelative(repository.updatedAt), + }, + ], + data.repositories, + { empty: 'Aucun dépôt dans cette organisation.' }, + ), + ), + + card( + 'Membres', + { subtitle: `${data.members.length} compte(s) Gitea` }, + table( + [ + { + label: 'Compte', + render: (member) => + h( + 'div', + { class: 'row' }, + member.avatar && + h('img', { + src: member.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: member.login }), + ), + }, + { label: 'Nom', render: (member) => member.fullName || '—' }, + { label: 'Admin', render: (member) => (member.isAdmin ? badge('Admin', 'danger') : '—') }, + { + label: 'Dernière connexion', + className: 'nowrap advanced-only', + render: (member) => formatRelative(member.lastLogin), + }, + ], + data.members, + ), + ), + + card( + 'Équipes', + { advanced: true }, + table( + [ + { label: 'Équipe', key: 'name' }, + { label: 'Description', render: (team) => team.description || '—' }, + { label: 'Permission', render: (team) => badge(team.permission ?? '—', 'info') }, + { + label: 'Tous les dépôts', + render: (team) => (team.includesAllRepositories ? 'Oui' : 'Non'), + }, + { + label: '', + render: (team) => + button( + 'Membres', + async () => { + const { members } = await api.get(`/api/organization/teams/${team.id}/members`); + await modal(`Membres de ${team.name}`, () => ({ + node: table( + [ + { label: 'Compte', key: 'login' }, + { label: 'Nom', render: (m) => m.fullName || '—' }, + ], + members, + ), + submit: () => true, + })); + }, + { tone: 'ghost' }, + ), + }, + ], + data.teams, + ), + ), + ); + }, + ); +} diff --git a/src/web/public/views/overview.js b/src/web/public/views/overview.js new file mode 100644 index 0000000..6ed05f7 --- /dev/null +++ b/src/web/public/views/overview.js @@ -0,0 +1,205 @@ +import { api } from '../core/api.js'; +import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js'; +import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js'; + +/** Landing page: state of the bot, the organization and the last deployments. */ + +const TONE = { + success: 'success', + failed: 'danger', + running: 'warning', + pending: 'neutral', + cancelled: 'neutral', +}; + +const EVENT_LABELS = { + 'web.login': 'Connexion au tableau de bord', + 'web.release.create': 'Release publiée', + 'deploy.success': 'Déploiement réussi', + 'deploy.failed': 'Déploiement en échec', + 'web.repository.create': 'Dépôt créé', + 'web.repository.delete': 'Dépôt supprimé', + 'web.announce': 'Annonce publiée', + 'ticket.close': 'Ticket clôturé', +}; + +const describeEvent = (type) => EVENT_LABELS[type] ?? type; + +function botCard(bot) { + return card( + 'Bot', + { subtitle: bot.online ? `Connecté en tant que ${bot.username}` : 'Hors ligne' }, + grid( + stat('État', bot.online ? 'En ligne' : 'Hors ligne', { tone: bot.online ? 'success' : 'danger' }), + stat('Latence', bot.ping === null ? '—' : `${bot.ping} ms`), + stat('Actif depuis', formatDuration(bot.uptimeMs)), + stat('Commandes', bot.commands), + ), + h( + 'div', + { class: 'row advanced-only' }, + badge(`Node ${bot.nodeVersion}`), + badge(`discord.js ${bot.discordJsVersion}`), + badge(`${bot.memoryMb} Mo de mémoire`), + ), + ); +} + +function guildCard(guild) { + if (!guild) return card('Serveur Discord', {}, h('p', { class: 'empty', text: 'Serveur introuvable.' })); + + return card( + 'Serveur Discord', + { subtitle: guild.name }, + grid( + stat('Membres', guild.memberCount, { tone: 'primary' }), + stat('Salons', guild.channelCount), + stat('Rôles', guild.roleCount), + stat('Boosts', `Niveau ${guild.boostTier}`), + ), + ); +} + +function giteaCard(gitea) { + if (!gitea.configured) { + return card( + 'Organisation', + {}, + h('p', { class: 'empty', text: 'Gitea n’est pas configuré. Renseigne GITEA_URL et GITEA_TOKEN.' }), + ); + } + + return card( + 'Organisation', + { subtitle: gitea.organization?.fullName || gitea.organization?.name || '—' }, + grid( + stat('Dépôts', gitea.repositoryCount, { tone: 'primary' }), + stat('Issues ouvertes', gitea.openIssues, { tone: gitea.openIssues > 0 ? 'warning' : 'neutral' }), + stat('PR ouvertes', gitea.openPulls), + stat('Étoiles', gitea.stars), + ), + h('h3', { text: 'Dépôts récemment actifs' }), + table( + [ + { + label: 'Dépôt', + render: (repository) => + h('a', { href: `#/repos/${repository.fullName}`, text: repository.fullName }), + }, + { label: 'Issues', className: 'num', render: (repository) => repository.openIssues ?? 0 }, + { label: 'PR', className: 'num', render: (repository) => repository.openPulls ?? 0 }, + { + label: 'Mise à jour', + className: 'nowrap', + render: (repository) => formatRelative(repository.updatedAt), + }, + ], + gitea.repositories, + ), + ); +} + +function activityCard(activity) { + const deployTotals = Object.fromEntries(activity.deployments.map((row) => [row.status, row.count])); + + return card( + 'Activité', + {}, + grid( + stat('Tickets ouverts', activity.openTickets, { + tone: activity.openTickets > 0 ? 'warning' : 'neutral', + }), + stat('Sondages', activity.polls), + stat('Salons vocaux', activity.voiceChannels), + stat('Déploiements réussis', deployTotals.success ?? 0, { tone: 'success' }), + stat('Déploiements en échec', deployTotals.failed ?? 0, { + tone: deployTotals.failed ? 'danger' : 'neutral', + }), + ), + activity.environments.length > 0 && + h( + 'div', + { class: 'stack' }, + h('h3', { text: 'Dernier déploiement par environnement' }), + table( + [ + { label: 'Environnement', key: 'environment' }, + { label: 'Dépôt', key: 'repository' }, + { label: 'Version', render: (row) => row.release_tag ?? '—' }, + { label: 'État', render: (row) => badge(row.status, TONE[row.status] ?? 'neutral') }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.finished_at) }, + ], + activity.environments, + ), + ), + ); +} + +function systemCard(database, features) { + return card( + 'Système', + { advanced: true, subtitle: database.path }, + grid( + stat('Taille de la base', formatBytes(database.sizeBytes)), + stat('Migrations', database.migrations.length), + stat('Webhooks', features.webhooks ? 'Activés' : 'Désactivés', { + tone: features.webhooks ? 'success' : 'neutral', + }), + stat('Gitea', features.gitea ? 'Connecté' : 'Non configuré', { + tone: features.gitea ? 'success' : 'warning', + }), + ), + table( + [ + { label: 'Table', key: 'name' }, + { label: 'Lignes', className: 'num', key: 'count' }, + ], + Object.entries(database.tables) + .map(([name, count]) => ({ name, count })) + .sort((a, b) => b.count - a.count), + ), + ); +} + +export function render(host, { state }) { + return renderAsync( + host, + () => api.get('/api/overview'), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Vue d’ensemble' }), + h('p', { + class: 'muted', + text: `Bonjour ${state.me.displayName ?? ''} — voici l’état de FWS en un coup d’œil.`, + }), + ), + ), + botCard(data.bot), + guildCard(data.bot.guild), + giteaCard(data.gitea), + activityCard(data.activity), + systemCard(data.database, data.features), + card( + 'Derniers événements', + { advanced: true }, + table( + [ + { label: 'Événement', render: (event) => describeEvent(event.type) }, + { label: 'Type', className: 'advanced-only', key: 'type' }, + { label: 'Auteur', render: (event) => (event.actor_id ? `<@${event.actor_id}>` : '—') }, + { label: 'Quand', className: 'nowrap', render: (event) => formatRelative(event.created_at) }, + ], + data.events, + ), + ), + ), + ); +} diff --git a/src/web/public/views/releases.js b/src/web/public/views/releases.js new file mode 100644 index 0000000..0a56946 --- /dev/null +++ b/src/web/public/views/releases.js @@ -0,0 +1,276 @@ +import { api, encodeRepo } from '../core/api.js'; +import { formatRelative, h, mount, richText } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + modal, + notice, + renderAsync, + select, + spinner, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Publishing releases and watching the deployments they trigger (M16-T08). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +/** Suggests the next patch version from the last tag, so the field is never empty. */ +function nextTag(lastTag) { + const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(lastTag ?? ''); + if (!match) return 'v0.1.0'; + const [, major, minor, patch] = match; + const prefix = lastTag.startsWith('v') ? 'v' : ''; + return `${prefix}${major}.${minor}.${Number(patch) + 1}`; +} + +async function publishRelease(base, repository, releases, branches, reload) { + const tag = input({ value: nextTag(releases[0]?.tag) }); + const name = input({ placeholder: 'Nom de la version (facultatif)' }); + const targetBranch = select( + branches.map((branch) => ({ value: branch.name, label: branch.name })), + { value: repository.defaultBranch }, + ); + const body = textarea({ placeholder: 'Notes de version…' }); + let draft = false; + let prerelease = false; + let deploy = true; + + const generate = button( + 'Générer les notes depuis les commits', + async () => { + const result = await api.post(`${base}/releases/notes`, { target: targetBranch.value }); + body.value = result.notes; + toast(`${result.commitCount} commit(s) analysé(s) depuis ${result.previousTag ?? 'le début'}.`, 'info'); + }, + { tone: 'ghost' }, + ); + + const confirmed = await modal( + 'Publier une release', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Tag', tag, { help: 'SemVer, comme le CHANGELOG généré depuis les commits.' }), + field('Nom', name), + field('Branche cible', targetBranch), + generate, + field('Notes de version', body), + toggle(false, (checked) => (draft = checked), 'Brouillon (non publié, aucune notification)'), + toggle(false, (checked) => (prerelease = checked), 'Préversion'), + toggle(true, (checked) => (deploy = checked), 'Lancer les déploiements automatiques configurés'), + ), + submit: () => tag.value.trim() !== '', + }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post(`${base}/releases`, { + tag: tag.value.trim(), + name: name.value.trim() || undefined, + target: targetBranch.value, + body: body.value, + draft, + prerelease, + deploy, + }); + + const deployed = result.deployments ?? []; + toast( + deployed.length > 0 + ? `Release ${result.release.tag} publiée, ${deployed.length} déploiement(s) déclenché(s).` + : `Release ${result.release.tag} publiée.`, + 'success', + ); + reload(); +} + +function releaseRow(base, level, reload) { + return [ + { + label: 'Version', + render: (release) => + h( + 'div', + {}, + h('a', { href: release.htmlUrl, target: '_blank', rel: 'noreferrer', text: release.tag }), + release.name && release.name !== release.tag && h('div', { class: 'muted', text: release.name }), + ), + }, + { + label: 'État', + render: (release) => + h( + 'div', + { class: 'row' }, + release.draft ? badge('Brouillon', 'neutral') : badge('Publiée', 'success'), + release.prerelease && badge('Préversion', 'warning'), + ), + }, + { label: 'Auteur', className: 'advanced-only', render: (release) => release.author ?? '—' }, + { + label: 'Publiée', + className: 'nowrap', + render: (release) => formatRelative(release.publishedAt ?? release.createdAt), + }, + { + label: '', + render: (release) => + h( + 'div', + { class: 'row' }, + button('Notes', () => showNotes(release), { tone: 'ghost' }), + level >= LEVELS.DEV && + release.draft && + button( + 'Publier', + async () => { + await api.patch(`${base}/releases/${release.id}`, { draft: false }); + toast('Release publiée.'); + reload(); + }, + { tone: 'success' }, + ), + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la release', `Supprimer ${release.tag} ?`))) return; + await api.delete(`${base}/releases/${release.id}`); + toast('Release supprimée.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ]; +} + +const showNotes = (release) => + modal(release.name || release.tag, () => ({ + node: richText(release.body || '_Aucune note._'), + submit: () => true, + })); + +export async function render(host, { state }) { + const level = state.me.accessLevel; + mount(host, spinner()); + + const params = new URLSearchParams(window.location.hash.split('?')[1] ?? ''); + const { repositories, configured } = await api.get('/api/repositories'); + + if (!configured || repositories.length === 0) { + mount(host, notice('Aucun dépôt Gitea accessible. Vérifie la configuration Gitea.', 'warning')); + return; + } + + const preferred = params.get('repo') || state.repository; + let current = repositories.find((item) => item.fullName === preferred) ?? repositories[0]; + + const picker = select( + repositories.map((item) => ({ value: item.fullName, label: item.fullName })), + { + value: current.fullName, + onChange: (event) => { + current = repositories.find((item) => item.fullName === event.target.value); + state.repository = current.fullName; + localStorage.setItem('fws.repository', current.fullName); + draw(); + }, + }, + ); + + const body = h('div', { class: 'stack' }); + + const draw = () => { + const base = `/api/repositories/${encodeRepo(current.fullName)}`; + renderAsync( + body, + async () => { + const [detail, releases, deployments] = await Promise.all([ + api.get(base), + api.get(`${base}/releases`, { limit: 30 }), + api.get('/api/deployments', { repository: current.fullName, limit: 15 }), + ]); + return { detail, releases: releases.releases, deployments: deployments.deployments }; + }, + (data) => + h( + 'div', + { class: 'stack' }, + card( + 'Releases', + { + subtitle: `${data.releases.length} version(s) sur ${current.fullName}`, + actions: + level >= LEVELS.DEV && + button( + 'Publier une release', + () => publishRelease(base, data.detail, data.releases, data.detail.branches, draw), + { tone: 'primary' }, + ), + }, + table(releaseRow(base, level, draw), data.releases, { empty: 'Aucune release publiée.' }), + ), + + card( + 'Déploiements liés', + { subtitle: 'Déclenchés par la publication d’une version ou lancés à la main.' }, + table( + [ + { label: 'Cible', key: 'target_name' }, + { label: 'Environnement', key: 'environment' }, + { label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' }, + { + label: 'État', + render: (row) => + badge( + row.status, + row.status === 'success' ? 'success' : row.status === 'failed' ? 'danger' : 'warning', + ), + }, + { label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) }, + ], + data.deployments, + { empty: 'Aucun déploiement pour ce dépôt.' }, + ), + ), + ), + ); + }; + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Releases' }), + h('p', { + class: 'muted', + text: 'Publie une version, génère ses notes depuis les commits et laisse les déploiements suivre.', + }), + ), + h('div', { style: { minWidth: '260px' } }, picker), + ), + body, + ), + ); + + draw(); +} diff --git a/src/web/public/views/repositories.js b/src/web/public/views/repositories.js new file mode 100644 index 0000000..59a7510 --- /dev/null +++ b/src/web/public/views/repositories.js @@ -0,0 +1,969 @@ +import { api, encodeRepo } from '../core/api.js'; +import { formatBytes, formatRelative, h, mount } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + confirmDangerous, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + spinner, + stat, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Repository list and the full management console of a single repository. */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +// --- List ------------------------------------------------------------------- + +function repositoryCard(repository) { + return h( + 'article', + { class: 'repo-card' }, + h('h3', {}, h('a', { href: `#/repos/${repository.fullName}`, text: repository.name })), + h('p', { class: 'muted', text: repository.description || 'Sans description.' }), + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + repository.language && badge(repository.language, 'info'), + ), + h( + 'div', + { class: 'repo-meta' }, + h('span', { text: `${repository.openIssues ?? 0} issues` }), + h('span', { text: `${repository.openPulls ?? 0} PR` }), + h('span', { text: `${repository.releases ?? 0} releases` }), + h('span', { text: formatRelative(repository.updatedAt) }), + ), + ); +} + +function renderList(host) { + return renderAsync( + host, + () => api.get('/api/repositories'), + (data) => { + if (!data.configured) { + return notice( + 'Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN` dans les paramètres.', + 'warning', + ); + } + + const search = input({ placeholder: 'Filtrer par nom…', type: 'search' }); + const list = h('div', { class: 'repo-list' }); + + const draw = () => { + const needle = search.value.trim().toLowerCase(); + const filtered = data.repositories.filter( + (repository) => + needle === '' || + repository.name.toLowerCase().includes(needle) || + (repository.description ?? '').toLowerCase().includes(needle), + ); + mount( + list, + filtered.length > 0 + ? filtered.map(repositoryCard) + : h('p', { class: 'empty', text: 'Aucun dépôt ne correspond.' }), + ); + }; + search.addEventListener('input', draw); + draw(); + + return h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Dépôts' }), + h('p', { class: 'muted', text: `${data.repositories.length} dépôt(s) dans l’organisation.` }), + ), + h('div', { style: { minWidth: '240px' } }, search), + ), + list, + ); + }, + ); +} + +// --- Detail ----------------------------------------------------------------- + +const TABS = [ + { id: 'overview', label: 'Aperçu', level: LEVELS.STAFF }, + { id: 'issues', label: 'Issues', level: LEVELS.STAFF }, + { id: 'pulls', label: 'Pull requests', level: LEVELS.STAFF }, + { id: 'commits', label: 'Commits', level: LEVELS.STAFF }, + { id: 'branches', label: 'Branches', level: LEVELS.STAFF, advanced: true }, + { id: 'people', label: 'Collaborateurs', level: LEVELS.STAFF, advanced: true }, + { id: 'hooks', label: 'Webhooks', level: LEVELS.DEV, advanced: true }, + { id: 'actions', label: 'Actions', level: LEVELS.STAFF, advanced: true }, + { id: 'settings', label: 'Réglages', level: LEVELS.DEV }, +]; + +const issueBadge = (issue) => + issue.state === 'open' ? badge('Ouverte', 'success') : badge('Fermée', 'neutral'); + +function issuesTab(base, level) { + const host = h('div', { class: 'stack' }); + let stateFilter = 'open'; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/issues`, { state: stateFilter, limit: 50 }), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'row' }, + select( + [ + { value: 'open', label: 'Ouvertes' }, + { value: 'closed', label: 'Fermées' }, + { value: 'all', label: 'Toutes' }, + ], + { + value: stateFilter, + onChange: (event) => { + stateFilter = event.target.value; + load(); + }, + }, + ), + button('Nouvelle issue', () => createIssue(base, load), { tone: 'primary' }), + ), + table( + [ + { label: '#', className: 'num', key: 'number' }, + { + label: 'Titre', + render: (issue) => + h( + 'div', + {}, + h('a', { href: issue.htmlUrl, target: '_blank', rel: 'noreferrer', text: issue.title }), + issue.labels.length > 0 && + h( + 'div', + { class: 'row' }, + issue.labels.map((label) => badge(label.name, 'info')), + ), + ), + }, + { label: 'État', render: issueBadge }, + { label: 'Auteur', render: (issue) => issue.author ?? '—' }, + { label: 'Maj', className: 'nowrap', render: (issue) => formatRelative(issue.updatedAt) }, + { + label: '', + render: (issue) => + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + issue.state === 'open' ? 'Fermer' : 'Rouvrir', + async () => { + await api.patch(`${base}/issues/${issue.number}`, { + state: issue.state === 'open' ? 'closed' : 'open', + }); + toast('Issue mise à jour.'); + load(); + }, + { tone: 'ghost' }, + ), + button('Commenter', () => commentIssue(base, issue, load), { tone: 'ghost' }), + ), + }, + ], + data.issues, + { empty: 'Aucune issue.' }, + ), + ), + ); + + load(); + return host; +} + +async function createIssue(base, reload) { + const title = input({ placeholder: 'Titre clair et actionnable' }); + const body = textarea({ placeholder: 'Contexte, étapes de reproduction, comportement attendu…' }); + + const confirmed = await modal( + 'Nouvelle issue', + () => ({ + node: h('div', { class: 'stack' }, field('Titre', title), field('Description', body)), + submit: () => title.value.trim().length >= 3, + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const issue = await api.post(`${base}/issues`, { title: title.value.trim(), body: body.value }); + toast(`Issue #${issue.number} créée.`); + reload(); +} + +async function commentIssue(base, issue, reload) { + const body = textarea({ placeholder: 'Ton commentaire…' }); + const confirmed = await modal( + `Commenter #${issue.number}`, + () => ({ node: field('Commentaire', body), submit: () => body.value.trim() !== '' }), + { confirmLabel: 'Publier', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post(`${base}/issues/${issue.number}/comments`, { body: body.value }); + toast('Commentaire publié.'); + reload(); +} + +function pullsTab(base, level) { + const host = h('div', { class: 'stack' }); + let stateFilter = 'open'; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/pulls`, { state: stateFilter, limit: 50 }), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'row' }, + select( + [ + { value: 'open', label: 'Ouvertes' }, + { value: 'closed', label: 'Fermées' }, + { value: 'all', label: 'Toutes' }, + ], + { + value: stateFilter, + onChange: (event) => { + stateFilter = event.target.value; + load(); + }, + }, + ), + level >= LEVELS.DEV && button('Nouvelle PR', () => createPull(base, load), { tone: 'primary' }), + ), + table( + [ + { label: '#', className: 'num', key: 'number' }, + { + label: 'Titre', + render: (pull) => + h('a', { href: pull.htmlUrl, target: '_blank', rel: 'noreferrer', text: pull.title }), + }, + { + label: 'Branches', + className: 'nowrap advanced-only', + render: (pull) => `${pull.head} → ${pull.base}`, + }, + { + label: 'État', + render: (pull) => + pull.merged + ? badge('Mergée', 'info') + : pull.draft + ? badge('Brouillon', 'neutral') + : issueBadge(pull), + }, + { label: 'Auteur', render: (pull) => pull.author ?? '—' }, + { label: 'Maj', className: 'nowrap', render: (pull) => formatRelative(pull.updatedAt) }, + { + label: '', + render: (pull) => + level >= LEVELS.DEV && + !pull.merged && + pull.state === 'open' && + button('Merger', () => mergePull(base, pull, load), { tone: 'success' }), + }, + ], + data.pulls, + { empty: 'Aucune pull request.' }, + ), + ), + ); + + load(); + return host; +} + +async function createPull(base, reload) { + const title = input({ placeholder: 'feat(scope): description' }); + const head = input({ placeholder: 'feat/ma-branche' }); + const baseBranch = input({ value: 'main' }); + const body = textarea({ placeholder: 'Ce que fait la PR et pourquoi.' }); + + const confirmed = await modal( + 'Nouvelle pull request', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Titre', title, { help: 'Format Conventional Commits, comme les commits FWS.' }), + field('Branche source', head), + field('Branche cible', baseBranch), + field('Description', body), + ), + submit: () => title.value.trim() !== '' && head.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const pull = await api.post(`${base}/pulls`, { + title: title.value.trim(), + head: head.value.trim(), + base: baseBranch.value.trim(), + body: body.value, + }); + toast(`PR #${pull.number} créée.`); + reload(); +} + +async function mergePull(base, pull, reload) { + const style = select( + [ + { value: 'squash', label: 'Squash (convention FWS)' }, + { value: 'merge', label: 'Merge commit' }, + { value: 'rebase', label: 'Rebase' }, + ], + { value: 'squash' }, + ); + let deleteBranch = true; + + const confirmed = await modal( + `Merger #${pull.number}`, + () => ({ + node: h( + 'div', + { class: 'stack' }, + h('p', { text: `${pull.head} → ${pull.base}` }), + field('Méthode', style), + toggle(true, (checked) => (deleteBranch = checked), 'Supprimer la branche après le merge'), + ), + submit: () => true, + }), + { confirmLabel: 'Merger', tone: 'primary' }, + ); + if (!confirmed) return; + + await api.post(`${base}/pulls/${pull.number}/merge`, { style: style.value, deleteBranch }); + toast('Pull request mergée.'); + reload(); +} + +function commitsTab(base, branches) { + const host = h('div', { class: 'stack' }); + let branch = ''; + + const load = () => + renderAsync( + host, + () => api.get(`${base}/commits`, { branch, limit: 40 }), + (data) => + h( + 'div', + { class: 'stack' }, + select( + [ + { value: '', label: 'Branche par défaut' }, + ...branches.map((item) => ({ value: item.name, label: item.name })), + ], + { + value: branch, + onChange: (event) => { + branch = event.target.value; + load(); + }, + }, + ), + table( + [ + { + label: 'Commit', + render: (commit) => + h('a', { + href: commit.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: commit.shortSha, + }), + }, + { label: 'Message', key: 'message' }, + { label: 'Auteur', render: (commit) => commit.authorLogin || commit.author || '—' }, + { label: 'Date', className: 'nowrap', render: (commit) => formatRelative(commit.date) }, + ], + data.commits, + { empty: 'Aucun commit.' }, + ), + ), + ); + + load(); + return host; +} + +function branchesTab(base, repository, level, refresh) { + return h( + 'div', + { class: 'stack' }, + level >= LEVELS.DEV && + h( + 'div', + { class: 'row' }, + button( + 'Nouvelle branche', + async () => { + const name = input({ placeholder: 'feat/ma-branche' }); + const from = input({ value: repository.defaultBranch ?? 'main' }); + const confirmed = await modal( + 'Créer une branche', + () => ({ + node: h('div', { class: 'stack' }, field('Nom', name), field('Depuis', from)), + submit: () => name.value.trim() !== '', + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + await api.post(`${base}/branches`, { name: name.value.trim(), from: from.value.trim() }); + toast('Branche créée.'); + refresh(); + }, + { tone: 'primary' }, + ), + ), + table( + [ + { + label: 'Branche', + render: (branch) => + h( + 'div', + { class: 'row' }, + h('strong', { text: branch.name }), + branch.name === repository.defaultBranch && badge('Par défaut', 'info'), + branch.protected && badge('Protégée', 'warning'), + ), + }, + { label: 'Dernier commit', render: (branch) => branch.commitMessage || '—' }, + { label: 'SHA', className: 'nowrap', render: (branch) => branch.commit ?? '—' }, + { label: 'Date', className: 'nowrap', render: (branch) => formatRelative(branch.commitAt) }, + { + label: '', + render: (branch) => + level >= LEVELS.DEV && + branch.name !== repository.defaultBranch && + !branch.protected && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la branche', `Supprimer « ${branch.name} » ?`))) return; + await api.delete(`${base}/branches`, { name: branch.name }); + toast('Branche supprimée.'); + refresh(); + }, + { tone: 'danger' }, + ), + }, + ], + repository.branches, + ), + ); +} + +function peopleTab(base, repository, level, refresh) { + return h( + 'div', + { class: 'stack' }, + level >= LEVELS.OWNER && + button( + 'Ajouter un collaborateur', + async () => { + const login = input({ placeholder: 'identifiant Gitea' }); + const permission = select( + [ + { value: 'read', label: 'Lecture' }, + { value: 'write', label: 'Écriture' }, + { value: 'admin', label: 'Administration' }, + ], + { value: 'write' }, + ); + const confirmed = await modal( + 'Ajouter un collaborateur', + () => ({ + node: h('div', { class: 'stack' }, field('Compte', login), field('Permission', permission)), + submit: () => login.value.trim() !== '', + }), + { confirmLabel: 'Ajouter', tone: 'primary' }, + ); + if (!confirmed) return; + await api.put(`${base}/collaborators/${encodeURIComponent(login.value.trim())}`, { + permission: permission.value, + }); + toast('Collaborateur ajouté.'); + refresh(); + }, + { tone: 'primary' }, + ), + table( + [ + { + label: 'Compte', + render: (user) => + h( + 'div', + { class: 'row' }, + user.avatar && + h('img', { + src: user.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: user.login }), + ), + }, + { label: 'Nom', render: (user) => user.fullName || '—' }, + { + label: 'Droits', + render: (user) => + h( + 'div', + { class: 'row' }, + user.permissions?.admin && badge('Admin', 'danger'), + user.permissions?.push && badge('Écriture', 'info'), + user.permissions?.pull && badge('Lecture', 'neutral'), + ), + }, + { + label: '', + render: (user) => + level >= LEVELS.OWNER && + button( + 'Retirer', + async () => { + if (!(await confirmAction('Retirer le collaborateur', `Retirer ${user.login} du dépôt ?`))) + return; + await api.delete(`${base}/collaborators/${encodeURIComponent(user.login)}`); + toast('Collaborateur retiré.'); + refresh(); + }, + { tone: 'danger' }, + ), + }, + ], + repository.collaborators, + ), + ); +} + +function hooksTab(base, level) { + const host = h('div', { class: 'stack' }); + + const load = () => + renderAsync( + host, + () => api.get(`${base}/hooks`), + (data) => + h( + 'div', + { class: 'stack' }, + notice( + 'Un webhook permet à Gitea de prévenir le bot en temps réel (issues, PR, commits, releases).', + 'info', + ), + level >= LEVELS.OWNER && + button( + 'Brancher ce dépôt sur le bot', + async () => { + if ( + !(await confirmAction( + 'Créer le webhook', + 'Gitea sera configuré pour envoyer les événements à ce bot, avec le secret déjà en place.', + )) + ) { + return; + } + const hook = await api.post(`${base}/hooks`, {}); + toast(`Webhook créé vers ${hook.url}.`); + load(); + }, + { tone: 'primary' }, + ), + table( + [ + { label: 'URL', key: 'url' }, + { label: 'Événements', render: (hook) => (hook.events ?? []).join(', ') }, + { + label: 'Actif', + render: (hook) => (hook.active ? badge('Oui', 'success') : badge('Non', 'neutral')), + }, + { + label: '', + render: (hook) => + level >= LEVELS.OWNER && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer le webhook', hook.url))) return; + await api.delete(`${base}/hooks/${hook.id}`); + toast('Webhook supprimé.'); + load(); + }, + { tone: 'danger' }, + ), + }, + ], + data.hooks, + { empty: 'Aucun webhook sur ce dépôt.' }, + ), + ), + ); + + load(); + return host; +} + +function actionsTab(base) { + const host = h('div', {}); + renderAsync( + host, + () => api.get(`${base}/actions`), + (data) => + data.available + ? table( + [ + { label: 'Workflow', key: 'name' }, + { label: 'Branche', key: 'headBranch' }, + { label: 'Commit', key: 'headSha' }, + { + label: 'État', + render: (task) => + badge( + task.conclusion ?? task.status ?? '—', + task.conclusion === 'success' + ? 'success' + : task.conclusion === 'failure' + ? 'danger' + : 'warning', + ), + }, + { label: 'Quand', className: 'nowrap', render: (task) => formatRelative(task.createdAt) }, + ], + data.tasks, + { empty: 'Aucune exécution.' }, + ) + : notice('Gitea Actions n’est pas disponible sur ce dépôt ou cette version de Gitea.', 'info'), + ); + return host; +} + +function settingsTab(base, repository, level, refresh) { + if (level < LEVELS.DEV) return notice('Réservé aux niveaux Dev et Owner.', 'warning'); + + const description = input({ value: repository.description ?? '' }); + const website = input({ value: repository.website ?? '' }); + const defaultBranch = select( + repository.branches.map((branch) => ({ value: branch.name, label: branch.name })), + { value: repository.defaultBranch }, + ); + + const switches = [ + ['has_issues', 'Issues activées', repository.hasIssues], + ['has_pull_requests', 'Pull requests activées', repository.hasPullRequests], + ['has_releases', 'Releases activées', repository.hasReleases], + ['has_wiki', 'Wiki activé', repository.hasWiki], + ['has_actions', 'Gitea Actions activées', repository.hasActions], + ['allow_squash_merge', 'Autoriser le squash merge', repository.allowSquash], + ['allow_merge_commits', 'Autoriser le merge commit', repository.allowMergeCommits], + ['allow_rebase', 'Autoriser le rebase', repository.allowRebase], + ['private', 'Dépôt privé', repository.private], + ['archived', 'Dépôt archivé (lecture seule)', repository.archived], + ]; + const values = Object.fromEntries(switches.map(([key, , value]) => [key, value])); + + return h( + 'div', + { class: 'stack' }, + card( + 'Identité', + { + actions: button( + 'Enregistrer', + async () => { + await api.patch(base, { + description: description.value, + website: website.value, + default_branch: defaultBranch.value, + }); + toast('Dépôt mis à jour.'); + refresh(); + }, + { tone: 'primary' }, + ), + }, + field('Description', description), + field('Site web', website), + field('Branche par défaut', defaultBranch), + ), + + card( + 'Fonctionnalités', + { + actions: button( + 'Appliquer', + async () => { + await api.patch(base, values); + toast('Réglages appliqués.'); + refresh(); + }, + { tone: 'primary' }, + ), + }, + ...switches.map(([key, label, value]) => + toggle(Boolean(value), (checked) => (values[key] = checked), label), + ), + ), + + level >= LEVELS.OWNER && + card( + 'Zone de danger', + { subtitle: 'Ces actions sont irréversibles.' }, + notice( + 'La suppression efface le dépôt, ses issues, ses PR et ses releases sur Gitea. Il n’y a pas de corbeille.', + 'error', + ), + button( + 'Supprimer ce dépôt', + async () => { + const ok = await confirmDangerous( + 'Supprimer le dépôt', + `Le dépôt ${repository.fullName} et tout son contenu seront définitivement supprimés.`, + repository.fullName, + ); + if (!ok) return; + await api.delete(base, { confirm: repository.fullName }); + toast('Dépôt supprimé.'); + window.location.hash = '#/repos'; + }, + { tone: 'danger' }, + ), + ), + ); +} + +function overviewTab(repository) { + const languages = Object.entries(repository.languages ?? {}); + const total = languages.reduce((sum, [, bytes]) => sum + bytes, 0) || 1; + + return h( + 'div', + { class: 'stack' }, + card( + 'Chiffres', + {}, + grid( + stat('Issues ouvertes', repository.openIssues, { + tone: repository.openIssues > 0 ? 'warning' : 'neutral', + }), + stat('PR ouvertes', repository.openPulls), + stat('Releases', repository.releases), + stat('Branches', repository.branches.length), + stat('Étoiles', repository.stars), + stat('Taille', formatBytes((repository.sizeKb ?? 0) * 1024)), + ), + ), + + repository.latestRelease && + card( + 'Dernière release', + { + actions: h('a', { + class: 'btn btn-ghost', + href: repository.latestRelease.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: '↗ Voir', + }), + }, + h( + 'p', + {}, + h('strong', { text: repository.latestRelease.tag }), + ' — ', + repository.latestRelease.name ?? '', + ), + h('p', { class: 'muted', text: `Publiée ${formatRelative(repository.latestRelease.publishedAt)}` }), + ), + + languages.length > 0 && + card( + 'Langages', + { advanced: true }, + ...languages + .sort((a, b) => b[1] - a[1]) + .map(([name, bytes]) => + h( + 'div', + {}, + h( + 'div', + { class: 'row', style: { justifyContent: 'space-between' } }, + h('span', { text: name }), + h('span', { class: 'muted', text: `${((bytes / total) * 100).toFixed(1)} %` }), + ), + h('div', { class: 'bar' }, h('span', { style: { width: `${(bytes / total) * 100}%` } })), + ), + ), + ), + + repository.topics.length > 0 && + card( + 'Sujets', + { advanced: true }, + h( + 'div', + { class: 'row' }, + repository.topics.map((topic) => badge(topic, 'info')), + ), + ), + + card( + 'Cloner', + { advanced: true }, + h('pre', {}, h('code', { text: `git clone ${repository.cloneUrl}` })), + repository.sshUrl && h('pre', {}, h('code', { text: `git clone ${repository.sshUrl}` })), + ), + ); +} + +async function renderDetail(host, state, owner, name) { + const base = `/api/repositories/${encodeRepo(`${owner}/${name}`)}`; + const level = state.me.accessLevel; + mount(host, spinner()); + + let repository; + try { + repository = await api.get(base); + } catch (error) { + mount(host, notice(error.message, 'error')); + return; + } + + const refresh = () => renderDetail(host, state, owner, name); + const body = h('div', { class: 'stack' }); + const tabs = TABS.filter((tab) => level >= tab.level && (!tab.advanced || state.mode === 'advanced')); + let active = tabs[0].id; + + const drawTab = () => { + const content = { + overview: () => overviewTab(repository), + issues: () => issuesTab(base, level), + pulls: () => pullsTab(base, level), + commits: () => commitsTab(base, repository.branches), + branches: () => branchesTab(base, repository, level, refresh), + people: () => peopleTab(base, repository, level, refresh), + hooks: () => hooksTab(base, level), + actions: () => actionsTab(base), + settings: () => settingsTab(base, repository, level, refresh), + }; + mount(body, content[active]()); + for (const control of tabBar.querySelectorAll('button')) { + control.classList.toggle('active', control.dataset.tab === active); + } + }; + + const tabBar = h( + 'div', + { class: 'tabs' }, + tabs.map((tab) => + h('button', { + type: 'button', + text: tab.label, + dataset: { tab: tab.id }, + onClick: () => { + active = tab.id; + drawTab(); + }, + }), + ), + ); + + mount( + host, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('p', { class: 'muted' }, h('a', { href: '#/repos', text: '← Tous les dépôts' })), + h('h1', { text: repository.fullName }), + h('p', { class: 'muted', text: repository.description || 'Sans description.' }), + h( + 'div', + { class: 'row' }, + repository.private ? badge('Privé', 'warning') : badge('Public', 'success'), + repository.archived && badge('Archivé', 'neutral'), + badge(`Branche ${repository.defaultBranch}`, 'info'), + ), + ), + h( + 'div', + { class: 'row' }, + h('a', { + class: 'btn btn-ghost', + href: repository.htmlUrl, + target: '_blank', + rel: 'noreferrer', + text: '↗ Gitea', + }), + h('a', { + class: 'btn btn-ghost', + href: `#/releases?repo=${repository.fullName}`, + text: 'Releases', + }), + ), + ), + repository.archived && notice('Ce dépôt est archivé : Gitea refusera toute écriture.', 'warning'), + tabBar, + body, + ), + ); + + drawTab(); +} + +export function render(host, { params, state }) { + if (params.length >= 2) return renderDetail(host, state, params[0], params[1]); + return renderList(host); +} diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js new file mode 100644 index 0000000..f565808 --- /dev/null +++ b/src/web/public/views/settings.js @@ -0,0 +1,476 @@ +import { api } from '../core/api.js'; +import { formatDate, formatRelative, h } from '../core/dom.js'; +import { + badge, + button, + card, + confirmAction, + confirmDangerous, + field, + grid, + input, + modal, + notice, + renderAsync, + select, + stat, + table, + toast, + toggle, +} from '../core/ui.js'; + +/** Settings tab: every knob the dashboard exposes, grouped by concern (M16-T10). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const keyValue = (rows) => + table( + [ + { label: 'Réglage', key: 'label' }, + { label: 'Valeur', render: (row) => row.value ?? '—' }, + ], + rows, + ); + +function behaviourCard(data, level, reload) { + if (level < LEVELS.DEV) { + return card( + 'Comportement du bot', + { subtitle: 'Lecture seule : le niveau Dev est requis pour modifier ces réglages.' }, + keyValue( + data.schema.map((setting) => ({ + label: setting.label, + value: String(data.values[setting.key]), + })), + ), + ); + } + + return card( + 'Comportement du bot', + { subtitle: 'Appliqué immédiatement, sans redémarrage.' }, + ...data.schema.map((setting) => { + const apply = async (value) => { + await api.put(`/api/settings/values/${setting.key}`, { value }); + toast(`« ${setting.label} » enregistré.`); + }; + + if (setting.type === 'bool') { + return h( + 'div', + {}, + toggle(Boolean(data.values[setting.key]), apply, setting.label), + h('div', { class: 'field-help', text: setting.help }), + ); + } + return field( + setting.label, + select( + setting.options.map((option) => ({ value: option, label: option })), + { value: data.values[setting.key], onChange: (event) => apply(event.target.value) }, + ), + { help: setting.help }, + ); + }), + button('Recharger', reload, { tone: 'ghost' }), + ); +} + +const testButton = (service, label) => + button( + label, + async () => { + const result = await api.post(`/api/settings/test/${service}`, {}); + toast(result.detail, result.ok ? 'success' : 'error'); + }, + { tone: 'ghost' }, + ); + +function connectionsCard(data) { + return h( + 'div', + { class: 'stack' }, + card( + 'Discord', + { actions: testButton('discord', 'Tester la connexion') }, + grid( + stat('Token', data.discord.tokenConfigured ? 'Configuré' : 'Manquant', { + tone: data.discord.tokenConfigured ? 'success' : 'danger', + }), + stat('Application ID', data.discord.clientId || '—'), + stat('Serveur', data.discord.guildId || '—'), + ), + h('h3', { class: 'advanced-only', text: 'Rôles FWS' }), + h( + 'div', + { class: 'advanced-only' }, + keyValue(Object.entries(data.discord.roles).map(([label, value]) => ({ label, value }))), + ), + h('h3', { class: 'advanced-only', text: 'Salons' }), + h( + 'div', + { class: 'advanced-only' }, + keyValue(Object.entries(data.discord.channels).map(([label, value]) => ({ label, value }))), + ), + ), + + card( + 'Gitea', + { actions: testButton('gitea', 'Tester le jeton') }, + grid( + stat('Instance', data.gitea.url || '—'), + stat('Organisation', data.gitea.owner || '—'), + stat('Dépôt principal', data.gitea.repo || '—'), + stat('Jeton', data.gitea.tokenConfigured ? 'Configuré' : 'Manquant', { + tone: data.gitea.tokenConfigured ? 'success' : 'warning', + }), + ), + h( + 'div', + { class: 'row advanced-only' }, + badge(`Délai ${data.gitea.timeoutMs} ms`), + badge(`${data.gitea.maxRetries} tentative(s) de secours`), + ), + ), + + card( + 'Webhooks Gitea', + {}, + grid( + stat('État', data.webhook.enabled ? 'Activés' : 'Désactivés', { + tone: data.webhook.enabled ? 'success' : 'neutral', + }), + stat('Secret', data.webhook.secretConfigured ? 'Configuré' : 'Manquant', { + tone: data.webhook.secretConfigured ? 'success' : 'warning', + }), + stat('Port', data.webhook.port), + ), + data.webhook.publicUrl && + h( + 'div', + {}, + h('p', { class: 'muted', text: 'URL à renseigner dans Gitea → Paramètres → Webhooks :' }), + h('pre', {}, h('code', { text: data.webhook.publicUrl })), + ), + data.webhook.enabled && + !data.webhook.secretConfigured && + notice('Les webhooks sont activés sans secret : tous les événements seront rejetés.', 'error'), + ), + + card( + 'Tableau de bord', + { advanced: true }, + grid( + stat('Écoute', `${data.web.host}:${data.web.port}`), + stat('URL publique', data.web.publicUrl || '—'), + stat('Connexion Discord', data.web.oauthConfigured ? 'Prête' : 'Non configurée', { + tone: data.web.oauthConfigured ? 'success' : 'warning', + }), + stat('Durée de session', `${data.web.sessionTtlHours} h`), + ), + h( + 'div', + {}, + h('p', { class: 'muted', text: 'URL de redirection à déclarer dans le Developer Portal :' }), + h('pre', {}, h('code', { text: data.web.redirectUri })), + ), + h( + 'div', + { class: 'row' }, + badge( + data.web.allowCommandDeploys ? 'Déploiements shell autorisés' : 'Déploiements shell bloqués', + data.web.allowCommandDeploys ? 'warning' : 'neutral', + ), + badge(data.web.allowRestart ? 'Redémarrage autorisé' : 'Redémarrage bloqué', 'neutral'), + badge(`${data.web.rateLimitPerMinute} req/min`, 'neutral'), + ), + ), + ); +} + +function sessionsCard(reload) { + const host = h('div', {}); + renderAsync( + host, + () => api.get('/api/settings/sessions'), + (data) => + table( + [ + { + label: 'Personne', + render: (session) => + h( + 'div', + { class: 'row' }, + session.avatar && + h('img', { + src: session.avatar, + alt: '', + width: 24, + height: 24, + style: { borderRadius: '50%' }, + }), + h('span', { text: session.display_name ?? session.username ?? '—' }), + session.current && badge('Cette session', 'info'), + ), + }, + { label: 'Niveau', render: (session) => badge(session.accessLabel, 'neutral') }, + { label: 'Origine', key: 'source' }, + { label: 'IP', className: 'advanced-only', key: 'ip' }, + { + label: 'Dernière activité', + className: 'nowrap', + render: (session) => formatRelative(session.last_seen_at), + }, + { + label: 'Expire', + className: 'nowrap advanced-only', + render: (session) => formatDate(session.expires_at), + }, + { + label: '', + render: (session) => + !session.current && + button( + 'Révoquer', + async () => { + if (!(await confirmAction('Révoquer la session', 'Cette personne devra se reconnecter.'))) + return; + await api.delete(`/api/settings/sessions/${session.id}`); + toast('Session révoquée.'); + reload(); + }, + { tone: 'danger' }, + ), + }, + ], + data.sessions, + { empty: 'Aucune session active.' }, + ), + ); + return card('Sessions ouvertes', { subtitle: 'Qui est connecté au tableau de bord en ce moment.' }, host); +} + +function tokensCard(reload) { + const host = h('div', {}); + + const load = () => + renderAsync( + host, + () => api.get('/api/settings/tokens'), + (data) => + table( + [ + { label: 'Nom', key: 'name' }, + { label: 'Préfixe', className: 'nowrap', key: 'prefix' }, + { label: 'Niveau', render: (token) => badge(token.accessLabel, 'neutral') }, + { label: 'Créé', className: 'nowrap', render: (token) => formatRelative(token.created_at) }, + { + label: 'Dernier usage', + className: 'nowrap', + render: (token) => (token.last_used_at ? formatRelative(token.last_used_at) : 'jamais'), + }, + { + label: 'État', + render: (token) => (token.active ? badge('Actif', 'success') : badge('Révoqué', 'neutral')), + }, + { + label: '', + render: (token) => + token.active && + button( + 'Révoquer', + async () => { + if (!(await confirmAction('Révoquer le jeton', token.name))) return; + await api.delete(`/api/settings/tokens/${token.id}`); + toast('Jeton révoqué.'); + load(); + }, + { tone: 'danger' }, + ), + }, + ], + data.tokens, + { empty: 'Aucun jeton d’API.' }, + ), + ); + + load(); + + return card( + 'Jetons d’API', + { + subtitle: 'Pour appeler cette API depuis un script ou une CI, sans compte Discord.', + actions: button( + 'Créer un jeton', + async () => { + const name = input({ placeholder: 'ci-deploiement' }); + const level = select( + [ + { value: '1', label: 'Staff — lecture' }, + { value: '2', label: 'Dev — écriture' }, + { value: '3', label: 'Owner — tout' }, + ], + { value: '1' }, + ); + const confirmed = await modal( + 'Nouveau jeton d’API', + () => ({ + node: h('div', { class: 'stack' }, field('Nom', name), field('Niveau d’accès', level)), + submit: () => name.value.trim().length >= 3, + }), + { confirmLabel: 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const result = await api.post('/api/settings/tokens', { + name: name.value.trim(), + accessLevel: Number(level.value), + }); + await modal( + 'Jeton créé', + () => ({ + node: h( + 'div', + { class: 'stack' }, + notice('Copie ce jeton maintenant : il ne sera plus jamais affiché.', 'warning'), + h('pre', {}, h('code', { text: result.token })), + h('p', { class: 'muted', text: 'À envoyer en en-tête `Authorization: Bearer `.' }), + ), + submit: () => true, + }), + { confirmLabel: 'J’ai copié' }, + ); + load(); + reload(); + }, + { tone: 'primary' }, + ), + }, + host, + ); +} + +function maintenanceCard(data) { + return card( + 'Maintenance', + { subtitle: `Base : ${data.runtime.databasePath}` }, + grid( + stat('Environnement', data.runtime.nodeEnv), + stat('Niveau de log', data.runtime.logLevel), + stat('Rétention', `${data.runtime.logRetentionDays} jours`), + stat('PID', data.runtime.pid), + ), + h( + 'div', + { class: 'row' }, + button( + 'Sauvegarder la base', + async () => { + const result = await api.post('/api/settings/backup', {}); + toast(`Sauvegarde écrite : ${result.file}`); + }, + { tone: 'primary' }, + ), + button( + 'Purger les anciens événements', + async () => { + const result = await api.post('/api/settings/purge', {}); + toast(`${result.events} événement(s) et ${result.sessions} session(s) supprimés.`); + }, + { tone: 'ghost' }, + ), + data.web.allowRestart && + button( + 'Redémarrer le bot', + async () => { + const ok = await confirmDangerous( + 'Redémarrer le bot', + 'Le processus va s’arrêter. Sans superviseur (systemd, pm2, Docker), il ne redémarrera pas tout seul.', + 'redemarrer', + ); + if (!ok) return; + await api.post('/api/settings/restart', {}); + toast('Redémarrage demandé.', 'info'); + }, + { tone: 'danger' }, + ), + ), + !data.web.allowRestart && + h('p', { class: 'muted', text: 'Le redémarrage depuis le site est désactivé (`WEB_ALLOW_RESTART`).' }), + ); +} + +function referenceCard(data) { + return card( + 'Référence', + { advanced: true, subtitle: 'Ce que le bot connaît, pour se repérer.' }, + h('h3', { text: 'Niveaux d’accès' }), + table( + [ + { label: 'Nom', key: 'name' }, + { label: 'Valeur', className: 'num', key: 'value' }, + { label: 'Libellé Discord', key: 'label' }, + ], + data.reference.accessLevels, + ), + h('h3', { text: 'Catégories de tickets' }), + table( + [ + { label: 'Identifiant', key: 'id' }, + { label: 'Libellé', key: 'label' }, + { label: 'Visible par', render: (category) => category.scope.join(', ') }, + ], + data.reference.ticketCategories, + ), + h('h3', { text: 'Types de notification' }), + h( + 'div', + { class: 'row' }, + data.reference.notificationTypes.map((type) => badge(type, 'info')), + ), + ); +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + + return renderAsync( + host, + () => api.get('/api/settings'), + (data) => + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Paramètres' }), + h('p', { + class: 'muted', + text: 'Les réglages du bot, ses connexions et la sécurité du tableau de bord.', + }), + ), + level >= LEVELS.OWNER && + h('a', { class: 'btn btn-primary', href: '#/setup', text: 'Assistant de configuration .env' }), + ), + + level >= LEVELS.OWNER && + notice( + 'Les valeurs du fichier .env ne sont lues qu’au démarrage. L’assistant les modifie, un redémarrage les applique.', + 'info', + ), + + behaviourCard(data, level, reload), + connectionsCard(data), + level >= LEVELS.OWNER ? sessionsCard(reload) : null, + level >= LEVELS.OWNER ? tokensCard(reload) : null, + level >= LEVELS.OWNER ? maintenanceCard(data) : null, + referenceCard(data), + ), + ); +} diff --git a/src/web/public/views/setup.js b/src/web/public/views/setup.js new file mode 100644 index 0000000..3014c9f --- /dev/null +++ b/src/web/public/views/setup.js @@ -0,0 +1,394 @@ +import { api } from '../core/api.js'; +import { h, mount, richText } from '../core/dom.js'; +import { button, card, field, input, notice, select, spinner, toast, toggle } from '../core/ui.js'; + +/** + * Step by step `.env` wizard (M16-T09). + * + * Walks through one section at a time: what the section is for, how to obtain + * each value, then the fields themselves with live validation. Nothing is + * written until « Enregistrer » is pressed, and the previous file is backed up. + */ + +const stateOf = (data) => ({ + data, + /** Only the fields the user actually touched. */ + edits: {}, + step: 0, + showAdvanced: false, + errors: { ...data.errors }, + warnings: [...data.warnings], + missing: [...data.missingRequired], + diff: [], + lastSave: null, +}); + +const valueOf = (view, key) => view.edits[key] ?? view.data.values[key] ?? ''; + +/** Step texts reference other fields, so they always show the values being typed. */ +const fillPlaceholders = (view, text) => + text + .replaceAll('{WEB_PUBLIC_URL}', valueOf(view, 'WEB_PUBLIC_URL') || 'https://ton-domaine') + .replaceAll('{WEBHOOK_PATH}', valueOf(view, 'WEBHOOK_PATH') || '/webhooks/gitea'); + +/** A section is complete when none of its variables is in error or missing. */ +function sectionStatus(view, sectionId) { + const variables = view.data.variables.filter((variable) => variable.section === sectionId); + const invalid = variables.some((variable) => view.errors[variable.key]); + const missing = variables.some((variable) => view.missing.includes(variable.key)); + const filled = variables.some((variable) => { + const value = valueOf(view, variable.key); + return value !== '' || view.data.secrets[variable.key]; + }); + return { invalid, missing, filled }; +} + +export async function render(host, { standalone = false } = {}) { + mount(host, spinner('Lecture de la configuration…')); + + const data = await api.get('/api/configuration'); + const view = stateOf(data); + const container = standalone + ? h('div', { class: 'main', style: { maxWidth: '1100px', margin: '0 auto' } }) + : h('div', {}); + mount(host, container); + + let validateTimer = null; + const scheduleValidation = () => { + clearTimeout(validateTimer); + validateTimer = setTimeout(async () => { + const result = await api.post('/api/configuration/validate', { values: view.edits }).catch(() => null); + if (!result) return; + view.errors = result.errors; + view.warnings = result.warnings; + view.missing = result.missingRequired; + view.diff = result.diff; + draw(); + }, 350); + }; + + const setValue = (key, value) => { + view.edits[key] = value; + scheduleValidation(); + }; + + function controlFor(variable) { + const key = variable.key; + const current = valueOf(view, key); + + if (variable.type === 'bool') { + return toggle(current === 'true', (checked) => { + setValue(key, checked ? 'true' : 'false'); + draw(); + }); + } + + if (variable.type === 'enum') { + return select( + variable.options.map((option) => ({ value: option, label: option })), + { value: current, onChange: (event) => setValue(key, event.target.value) }, + ); + } + + const control = input({ + type: variable.type === 'secret' ? 'password' : 'text', + value: current, + placeholder: variable.placeholder ?? variable.default ?? '', + autocomplete: 'off', + spellcheck: 'false', + onInput: (event) => setValue(key, event.target.value), + }); + + if (variable.type !== 'secret' && !variable.generator && !variable.testable) return control; + + const extras = [control]; + if (variable.generator) { + extras.push( + button( + 'Générer', + async () => { + const { value } = await api.post('/api/configuration/generate', { kind: variable.generator }); + control.value = value; + setValue(key, value); + toast('Secret généré. Il ne sera visible qu’ici.', 'info'); + }, + { tone: 'ghost' }, + ), + ); + } + if (variable.testable) { + extras.push( + button( + 'Tester', + async () => { + const result = await api.post(`/api/configuration/test/${variable.testable}`, { + values: view.edits, + }); + toast(result.detail, result.ok ? (result.warning ? 'info' : 'success') : 'error'); + }, + { tone: 'ghost' }, + ), + ); + } + return h('div', { class: 'secret-row' }, ...extras); + } + + function fieldFor(variable) { + const key = variable.key; + const isSecretSet = variable.type === 'secret' && view.data.secrets[key] && !(key in view.edits); + const help = [ + variable.help, + isSecretSet ? 'Une valeur est déjà enregistrée : laisse vide pour la conserver.' : null, + variable.restartRequired ? 'Prise en compte au prochain démarrage du bot.' : null, + ] + .filter(Boolean) + .join(' '); + + const wrapper = field(`${variable.label}${variable.required ? ' *' : ''}`, controlFor(variable), { + help, + error: view.errors[key], + }); + wrapper.append( + h('span', { class: 'field-help', text: key, style: { fontFamily: 'var(--mono)', opacity: '0.6' } }), + ); + return variable.advanced ? h('div', { class: 'advanced-wrapper' }, wrapper) : wrapper; + } + + async function showPreview() { + const { content } = await api.post('/api/configuration/preview', { values: view.edits }); + mount( + previewHost, + card( + 'Aperçu du fichier .env', + { subtitle: 'Les secrets sont masqués dans cet aperçu.' }, + h('pre', {}, h('code', { text: content })), + ), + ); + } + + async function save({ force = false } = {}) { + try { + const result = await api.post('/api/configuration/save', { values: view.edits, force }); + view.lastSave = result; + view.edits = {}; + view.data = await api.get('/api/configuration'); + view.errors = view.data.errors; + view.warnings = view.data.warnings; + view.missing = view.data.missingRequired; + view.diff = []; + toast(result.written ? 'Configuration enregistrée.' : 'Aucun changement à enregistrer.', 'success'); + draw(); + } catch (error) { + toast(error.message, 'error'); + if (error.details) { + view.errors = error.details; + draw(); + } + } + } + + const previewHost = h('div', {}); + + function stepList() { + return h( + 'div', + { class: 'wizard-steps' }, + view.data.sections.map((section, index) => { + const status = sectionStatus(view, section.id); + const classes = ['wizard-step']; + if (index === view.step) classes.push('active'); + if (status.invalid || status.missing) classes.push('invalid'); + else if (status.filled) classes.push('done'); + + return h( + 'button', + { + class: classes.join(' '), + type: 'button', + onClick: () => { + view.step = index; + draw(); + }, + }, + h('span', { class: 'dot', text: status.invalid || status.missing ? '!' : String(index + 1) }), + h( + 'span', + {}, + h('strong', { text: section.title }), + h('span', { class: 'muted', text: section.summary }), + ), + ); + }), + ); + } + + function stepBody() { + const section = view.data.sections[view.step]; + const variables = view.data.variables.filter( + (variable) => variable.section === section.id && (view.showAdvanced || !variable.advanced), + ); + const hiddenCount = view.data.variables.filter( + (variable) => variable.section === section.id && variable.advanced, + ).length; + + return card( + section.title, + { + subtitle: section.summary, + actions: [ + button( + view.step === 0 ? '' : '← Précédent', + () => { + view.step = Math.max(0, view.step - 1); + draw(); + }, + { tone: 'ghost', disabled: view.step === 0 }, + ), + button( + 'Suivant →', + () => { + view.step = Math.min(view.data.sections.length - 1, view.step + 1); + draw(); + }, + { tone: 'ghost', disabled: view.step === view.data.sections.length - 1 }, + ), + ], + }, + section.intro && h('p', { text: section.intro }), + + section.steps?.length > 0 && + h( + 'ol', + { class: 'steps-list' }, + section.steps.map((step) => h('li', {}, richText(fillPlaceholders(view, step), 'rich-inline'))), + ), + + section.links?.length > 0 && + h( + 'div', + { class: 'row' }, + section.links.map((link) => + h('a', { + class: 'btn btn-ghost', + href: link.url, + target: '_blank', + rel: 'noreferrer', + text: `↗ ${link.label}`, + }), + ), + ), + + hiddenCount > 0 && + toggle( + view.showAdvanced, + (checked) => { + view.showAdvanced = checked; + draw(); + }, + `Afficher les ${hiddenCount} options avancées`, + ), + + ...variables.map(fieldFor), + ); + } + + function summary() { + const blocking = view.missing.length > 0 || Object.keys(view.errors).length > 0; + + return card( + 'Enregistrement', + { + subtitle: view.data.exists + ? 'Le fichier .env actuel sera sauvegardé avant d’être remplacé.' + : 'Aucun .env pour l’instant : il sera créé avec les permissions 600.', + actions: [ + button('Aperçu', showPreview, { tone: 'ghost' }), + button('Enregistrer le .env', () => save(), { tone: 'primary', disabled: blocking }), + ], + }, + + view.missing.length > 0 && + notice(`Valeurs obligatoires manquantes : ${view.missing.join(', ')}.`, 'error'), + + Object.keys(view.errors).length > 0 && + notice( + `${Object.keys(view.errors).length} champ(s) invalide(s) : ${Object.keys(view.errors).join(', ')}.`, + 'error', + ), + + ...view.warnings.map((warning) => notice(warning, 'warning')), + + view.diff.length > 0 && + h( + 'div', + { class: 'stack' }, + h('h3', { text: `${view.diff.length} changement(s) en attente` }), + h( + 'div', + { class: 'diff stack' }, + view.diff.map((entry) => + h( + 'div', + {}, + h('strong', { text: `${entry.key} ` }), + h('del', { text: entry.before || '(vide)' }), + ' → ', + h('ins', { text: entry.after || '(vide)' }), + entry.restartRequired && h('span', { class: 'muted', text: ' · redémarrage requis' }), + ), + ), + ), + ), + + view.lastSave?.written && + notice( + `Fichier écrit.${view.lastSave.backup ? ` Sauvegarde : ${view.lastSave.backup}.` : ''}${ + view.lastSave.restartRequired ? ' Redémarre le bot pour appliquer les changements.' : '' + }`, + 'success', + ), + + view.data.unknownKeys.length > 0 && + notice( + `Variables inconnues conservées telles quelles : ${view.data.unknownKeys.join(', ')}.`, + 'info', + ), + ); + } + + function draw() { + mount( + container, + h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Configuration du bot' }), + h('p', { + class: 'muted', + text: 'Chaque valeur est expliquée, vérifiée puis écrite dans le fichier .env. Rien n’est enregistré avant ta validation.', + }), + ), + ), + standalone && + notice( + 'Session d’amorçage : seule cette page est accessible. Une fois le .env enregistré, redémarre le bot et connecte-toi avec Discord.', + 'info', + ), + h( + 'div', + { class: 'wizard' }, + stepList(), + h('div', { class: 'stack' }, stepBody(), summary(), previewHost), + ), + ), + ); + } + + draw(); +} diff --git a/src/web/server.js b/src/web/server.js new file mode 100644 index 0000000..e58550f --- /dev/null +++ b/src/web/server.js @@ -0,0 +1,136 @@ +import { createServer } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { env } from '../config/env.js'; +import { ExternalApiError, PermissionDeniedError, UserFacingError } from '../core/errors.js'; +import { createLogger } from '../core/logger.js'; +import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js'; +import { registerApiRoutes } from './api/index.js'; +import { authenticate, assertSameOrigin } from './auth/session.js'; +import { authorize } from './auth/guard.js'; +import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; +import { createRouter } from './router.js'; + +/** HTTP server of the dashboard (M16-T01). */ + +const log = createLogger('web'); +const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public'); + +/** Sliding window per client address, reset every minute. */ +function createRateLimiter(limit) { + const hits = new Map(); + let windowStart = Date.now(); + + return (key) => { + const now = Date.now(); + if (now - windowStart >= 60_000) { + hits.clear(); + windowStart = now; + } + const count = (hits.get(key) ?? 0) + 1; + hits.set(key, count); + return count <= limit; + }; +} + +function statusOf(error) { + if (error instanceof HttpError) return error.status; + if (error instanceof PermissionDeniedError) return 403; + if (error instanceof UserFacingError) return 400; + if (error instanceof ExternalApiError) return 502; + return 500; +} + +/** + * Builds the request handler. Exported on its own so the tests can drive it + * without opening a socket. + */ +export function createHandler({ client = null, setupOnly = false, startedAt = Date.now() } = {}) { + const router = registerApiRoutes(createRouter(), { setupOnly }); + const context = { client, setupOnly, startedAt }; + const allowWithinRate = createRateLimiter(env.web.rateLimitPerMinute); + + // The webhook shares the port when both servers are configured on it. + const sharesWebhookPort = env.webhook.enabled && env.webhook.port === env.web.port; + + return async function handle(request, response) { + const url = new URL(request.url, `http://${request.headers.host ?? 'localhost'}`); + const pathname = url.pathname; + + if (sharesWebhookPort && request.method === 'POST' && pathname === env.webhook.path) { + try { + const rawBody = await readRawBody(request); + response.writeHead(await handleGiteaWebhook(client, request.headers, rawBody)).end(); + } catch (error) { + log.error('Webhook handling failed', error); + response.writeHead(500).end(); + } + return; + } + + const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/'); + if (!isApi) { + // Anything else is the single page application; unknown paths fall back to + // its shell so client-side routing works on a hard refresh. + const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' }); + if (!served) sendEmpty(response, 404); + return; + } + + if (!allowWithinRate(request.socket.remoteAddress ?? 'unknown')) { + sendJson(response, 429, { error: 'Trop de requêtes, réessaie dans une minute.' }); + return; + } + + try { + const route = router.resolve(request.method, pathname); + const actor = authenticate(request); + assertSameOrigin(request, actor); + authorize(actor, route.options); + + const body = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method) + ? await readJsonBody(request) + : {}; + + const result = await route.handler({ + request, + response, + params: route.params, + query: url.searchParams, + body, + actor, + context, + }); + + // A handler that wrote the response itself (a redirect) returns nothing. + if (!response.headersSent) sendJson(response, 200, result ?? { ok: true }); + } catch (error) { + const status = statusOf(error); + if (status >= 500) log.error(`${request.method} ${pathname} failed`, error); + else log.debug(`${request.method} ${pathname} rejected with ${status}`, { message: error.message }); + + if (!response.headersSent) { + sendJson(response, status, { + error: status >= 500 ? 'Une erreur interne est survenue.' : error.message, + ...(error.details && { details: error.details }), + }); + } + } + }; +} + +export function startWebServer({ client = null, setupOnly = false } = {}) { + const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() })); + + server.listen(env.web.port, env.web.host, () => { + const url = env.web.publicUrl || `http://${env.web.host}:${env.web.port}`; + log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly }); + }); + server.on('error', (error) => log.error('Dashboard server error', error)); + return server; +} + +/** True when the webhook server does not need its own port. */ +export function webhookSharesWebPort() { + return env.web.enabled && env.webhook.enabled && env.webhook.port === env.web.port; +} From bd7fdea2759060210be464e262c59422304bd041 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:52 +0200 Subject: [PATCH 10/51] test(web): cover the router, configuration, auth, deployments and server The schema test compares the declared variables against `.env.example`, so the two cannot drift apart. The server tests drive the real handler over a loopback socket rather than a mock, which is what caught the health probe missing from bootstrap mode and the deployments recorded under the wrong guild. Co-Authored-By: Claude Opus 5 (1M context) --- tests/web-auth.test.js | 229 ++++++++++++++++++++++++++++++++ tests/web-configuration.test.js | 184 +++++++++++++++++++++++++ tests/web-deployments.test.js | 224 +++++++++++++++++++++++++++++++ tests/web-router.test.js | 46 +++++++ tests/web-server.test.js | 179 +++++++++++++++++++++++++ 5 files changed, 862 insertions(+) create mode 100644 tests/web-auth.test.js create mode 100644 tests/web-configuration.test.js create mode 100644 tests/web-deployments.test.js create mode 100644 tests/web-router.test.js create mode 100644 tests/web-server.test.js diff --git a/tests/web-auth.test.js b/tests/web-auth.test.js new file mode 100644 index 0000000..272e59e --- /dev/null +++ b/tests/web-auth.test.js @@ -0,0 +1,229 @@ +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + createApiToken, + getLiveApiTokenByHash, + listSessions, + revokeApiToken, +} from '../src/database/repositories/web-session-repository.js'; +import { authorize } from '../src/web/auth/guard.js'; +import { resolveAccessLevel } from '../src/web/auth/discord-oauth.js'; +import { + assertSameOrigin, + authenticate, + closeSession, + hashToken, + openSession, +} from '../src/web/auth/session.js'; + +/** Minimal stand-ins for the Node request and response objects. */ +const fakeRequest = (headers = {}, method = 'GET') => ({ + method, + headers: { 'user-agent': 'node-test', ...headers }, + socket: { remoteAddress: '127.0.0.1' }, +}); + +function fakeResponse() { + const headers = {}; + return { + headers, + setHeader: (name, value) => { + headers[name] = value; + }, + getHeader: (name) => headers[name], + }; +} + +const cookieOf = (response) => { + const raw = [].concat(response.getHeader('Set-Cookie') ?? [])[0] ?? ''; + return raw.split(';')[0]; +}; + +describe('access guard', () => { + it('lets a public route through without an actor', () => { + assert.doesNotThrow(() => authorize(null, { public: true })); + }); + + it('refuses an anonymous caller with 401', () => { + assert.throws(() => authorize(null, { access: ACCESS_LEVELS.STAFF }), { status: 401 }); + }); + + it('compares the actor level against the route requirement', () => { + const staff = { accessLevel: ACCESS_LEVELS.STAFF, source: 'discord' }; + assert.doesNotThrow(() => authorize(staff, { access: ACCESS_LEVELS.STAFF })); + assert.throws(() => authorize(staff, { access: ACCESS_LEVELS.OWNER }), { status: 403 }); + }); + + it('defaults to Owner when a route forgets to declare its level', () => { + assert.throws(() => authorize({ accessLevel: ACCESS_LEVELS.DEV, source: 'discord' }, {}), { + status: 403, + }); + }); + + it('confines a bootstrap session to the configuration routes', () => { + const setup = { accessLevel: ACCESS_LEVELS.OWNER, source: 'setup' }; + assert.doesNotThrow(() => authorize(setup, { access: ACCESS_LEVELS.OWNER, setup: true })); + assert.throws(() => authorize(setup, { access: ACCESS_LEVELS.STAFF }), { status: 403 }); + }); +}); + +describe('cross-site protection', () => { + it('never blocks a read', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'GET'), { kind: 'session' })); + }); + + it('requires the dashboard header on a write', () => { + assert.throws(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'session' }), { status: 403 }); + assert.doesNotThrow(() => + assertSameOrigin(fakeRequest({ 'x-requested-with': 'fws-dashboard' }, 'POST'), { kind: 'session' }), + ); + }); + + it('rejects a write coming from another origin', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://evil.example', host: 'bot.example' }, + 'POST', + ); + assert.throws(() => assertSameOrigin(request, { kind: 'session' }), { status: 403 }); + }); + + it('accepts a write from the served host', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://bot.example', host: 'bot.example' }, + 'POST', + ); + assert.doesNotThrow(() => assertSameOrigin(request, { kind: 'session' })); + }); + + it('exempts machine tokens, which carry no cookie', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'api-token' })); + }); +}); + +describe('dashboard sessions', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_sessions; DELETE FROM web_api_tokens;')); + + const login = (level = ACCESS_LEVELS.DEV) => { + const response = fakeResponse(); + const session = openSession(fakeRequest(), response, { + user: { id: '42', username: 'kim', displayName: 'Kim', avatar: null }, + accessLevel: level, + }); + return { session, cookie: cookieOf(response) }; + }; + + it('stores only the hash of the cookie value', () => { + const { session, cookie } = login(); + const token = decodeURIComponent(cookie.split('=')[1]); + + assert.notEqual(session.token_hash, token); + assert.equal(session.token_hash, hashToken(token)); + }); + + it('identifies the caller from its cookie', () => { + const { cookie } = login(ACCESS_LEVELS.STAFF); + const actor = authenticate(fakeRequest({ cookie })); + + assert.equal(actor.kind, 'session'); + assert.equal(actor.userId, '42'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.STAFF); + }); + + it('returns null for an unknown or absent cookie', () => { + assert.equal(authenticate(fakeRequest()), null); + assert.equal(authenticate(fakeRequest({ cookie: 'fws_session=inventé' })), null); + }); + + it('ignores an expired session', () => { + const { cookie } = login(); + getDatabase().exec("UPDATE web_sessions SET expires_at = datetime('now', '-1 hour')"); + assert.equal(authenticate(fakeRequest({ cookie })), null); + }); + + it('closes a session and clears the cookie', () => { + const { cookie } = login(); + const response = fakeResponse(); + closeSession(fakeRequest({ cookie }), response); + + assert.equal(authenticate(fakeRequest({ cookie })), null); + assert.match([].concat(response.getHeader('Set-Cookie'))[0], /Max-Age=0/); + }); + + it('lists the live sessions', () => { + login(); + login(ACCESS_LEVELS.OWNER); + assert.equal(listSessions().length, 2); + }); +}); + +describe('api tokens', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_api_tokens;')); + + const issue = () => { + const token = 'fws_test-token-value'; + const id = createApiToken({ + name: 'ci', + tokenHash: hashToken(token), + prefix: token.slice(0, 12), + accessLevel: ACCESS_LEVELS.DEV, + }); + return { id, token }; + }; + + it('authenticates a bearer token', () => { + const { token } = issue(); + const actor = authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + + assert.equal(actor.kind, 'api-token'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.DEV); + }); + + it('records the last usage', () => { + const { token } = issue(); + authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + assert.ok(getLiveApiTokenByHash(hashToken(token)).last_used_at); + }); + + it('refuses a revoked token', () => { + const { id, token } = issue(); + revokeApiToken(id); + assert.equal(authenticate(fakeRequest({ authorization: `Bearer ${token}` })), null); + }); + + it('refuses an unknown token', () => { + assert.equal(authenticate(fakeRequest({ authorization: 'Bearer nope' })), null); + }); +}); + +describe('oauth access level', () => { + const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' }; + + it('gives Owner to the guild owner whatever their roles', () => { + const level = resolveAccessLevel({ member: { roles: [] }, userId: '1', guildOwnerId: '1', roles }); + assert.equal(level, ACCESS_LEVELS.OWNER); + }); + + it('reads the highest matching role', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['r-staff', 'r-dev'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.DEV, + ); + }); + + it('falls back to plain member', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['autre'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.USER, + ); + }); + + it('returns null when the visitor is not in the guild', () => { + assert.equal(resolveAccessLevel({ member: null, userId: '2', guildOwnerId: '1', roles }), null); + }); +}); diff --git a/tests/web-configuration.test.js b/tests/web-configuration.test.js new file mode 100644 index 0000000..38af388 --- /dev/null +++ b/tests/web-configuration.test.js @@ -0,0 +1,184 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { + diffValues, + maskValues, + mergeValues, + parseEnv, + renderEnvFile, + secretStatus, + writeEnvFile, +} from '../src/web/services/env-file.js'; +import { + BY_KEY, + SECTIONS, + VARIABLES, + crossCheck, + requiredKeys, + validateAll, + validateValue, +} from '../src/web/services/env-schema.js'; + +describe('env schema', () => { + it('declares every variable inside a known section', () => { + const sectionIds = new Set(SECTIONS.map((section) => section.id)); + for (const variable of VARIABLES) { + assert.ok(sectionIds.has(variable.section), `${variable.key} points at an unknown section`); + } + }); + + it('documents every variable with a label and a help text', () => { + for (const variable of VARIABLES) { + assert.ok(variable.label?.length > 0, `${variable.key} has no label`); + assert.ok(variable.help?.length > 0, `${variable.key} has no help`); + } + }); + + it('covers the variables the bot refuses to start without', () => { + assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']); + }); + + it('mirrors the keys used by .env.example', () => { + const example = parseEnv(readFileSync('.env.example', 'utf8')); + for (const key of Object.keys(example)) { + assert.ok(key in BY_KEY, `${key} is in .env.example but missing from the schema`); + } + for (const variable of VARIABLES) { + assert.ok(variable.key in example, `${variable.key} is in the schema but missing from .env.example`); + } + }); + + it('validates Discord identifiers', () => { + assert.equal(validateValue('DISCORD_GUILD_ID', '123456789012345678'), null); + assert.match(validateValue('DISCORD_GUILD_ID', 'abc'), /17 à 20 chiffres/); + }); + + it('validates numbers against their bounds', () => { + assert.equal(validateValue('WEB_PORT', '3080'), null); + assert.match(validateValue('WEB_PORT', '99999'), /Maximum/); + assert.match(validateValue('WEB_PORT', 'abc'), /nombre entier/); + }); + + it('validates booleans, enums and urls', () => { + assert.equal(validateValue('WEB_ENABLED', 'true'), null); + assert.match(validateValue('WEB_ENABLED', 'oui'), /true` ou `false/); + assert.equal(validateValue('LOG_LEVEL', 'debug'), null); + assert.match(validateValue('LOG_LEVEL', 'verbose'), /Valeurs possibles/); + assert.equal(validateValue('GITEA_URL', 'https://gitea.example.org'), null); + assert.match(validateValue('GITEA_URL', 'gitea.example.org'), /URL invalide/); + }); + + it('accepts an empty optional value but not an empty required one', () => { + assert.equal(validateValue('ROLE_OWNER_ID', ''), null); + assert.match(validateValue('DISCORD_TOKEN', ''), /obligatoire/); + }); + + it('reports every invalid key at once', () => { + const errors = validateAll({ DISCORD_TOKEN: 'x', DISCORD_CLIENT_ID: 'nope', DISCORD_GUILD_ID: '' }); + assert.ok(errors.DISCORD_CLIENT_ID); + assert.ok(errors.DISCORD_GUILD_ID); + assert.equal(errors.DISCORD_TOKEN, undefined); + }); + + it('warns about combinations no single field can catch', () => { + const warnings = crossCheck({ WEBHOOK_ENABLED: 'true', GITEA_WEBHOOK_SECRET: '' }); + assert.ok(warnings.some((warning) => warning.includes('rejetés'))); + }); + + it('warns when the dashboard is exposed without HTTPS', () => { + const warnings = crossCheck({ + WEB_ENABLED: 'true', + WEB_HOST: '0.0.0.0', + WEB_PUBLIC_URL: 'http://bot.example.org', + DISCORD_CLIENT_SECRET: 'x', + WEB_SESSION_SECRET: 'y', + }); + assert.ok(warnings.some((warning) => warning.includes('en clair'))); + }); +}); + +describe('env file', () => { + let directory; + let file; + + before(() => { + directory = mkdtempSync(path.join(tmpdir(), 'fws-env-')); + file = path.join(directory, '.env'); + }); + after(() => rmSync(directory, { recursive: true, force: true })); + + it('parses quoted, unquoted and commented lines', () => { + const values = parseEnv('# comment\nA=1\nB="deux mots"\nC=\'trois\'\nexport D=4\ninvalid\n'); + assert.deepEqual(values, { A: '1', B: 'deux mots', C: 'trois', D: '4' }); + }); + + it('renders a file that documents every variable', () => { + const content = renderEnvFile({ DISCORD_TOKEN: 'secret', WEB_PORT: '3080' }); + for (const variable of VARIABLES) { + assert.ok(content.includes(`${variable.key}=`), `${variable.key} is missing from the rendered file`); + assert.ok(content.includes(variable.label), `${variable.label} is missing from the rendered file`); + } + }); + + it('keeps variables it does not know about', () => { + const content = renderEnvFile({}, { CUSTOM_THING: 'valeur' }); + assert.match(content, /CUSTOM_THING=valeur/); + }); + + it('quotes values that need it', () => { + const content = renderEnvFile({ GITEA_OWNER: 'deux mots' }); + assert.match(content, /GITEA_OWNER="deux mots"/); + }); + + it('writes the file with 600 permissions and backs up the previous one', () => { + writeFileSync(file, 'DISCORD_TOKEN=ancien\n'); + const result = writeEnvFile({ DISCORD_TOKEN: 'nouveau' }, { file }); + + assert.ok(result.backup, 'no backup was made'); + assert.match(readFileSync(result.backup, 'utf8'), /ancien/); + assert.match(readFileSync(file, 'utf8'), /DISCORD_TOKEN=nouveau/); + assert.equal(statSync(file).mode & 0o777, 0o600); + }); + + it('keeps the stored secret when the submitted one is empty', () => { + const merged = mergeValues( + { DISCORD_TOKEN: 'garde-moi', GITEA_OWNER: 'FWS' }, + { DISCORD_TOKEN: '', GITEA_OWNER: 'AUTRE' }, + ); + assert.equal(merged.DISCORD_TOKEN, 'garde-moi'); + assert.equal(merged.GITEA_OWNER, 'AUTRE'); + }); + + it('ignores keys that are not part of the schema', () => { + const merged = mergeValues({}, { NOT_A_REAL_KEY: 'x' }); + assert.equal(merged.NOT_A_REAL_KEY, undefined); + }); + + it('never sends a secret back to the browser', () => { + const masked = maskValues({ DISCORD_TOKEN: 'tres-secret', GITEA_OWNER: 'FWS' }); + assert.equal(masked.DISCORD_TOKEN, ''); + assert.equal(masked.GITEA_OWNER, 'FWS'); + + const status = secretStatus({ DISCORD_TOKEN: 'tres-secret' }); + assert.equal(status.DISCORD_TOKEN, true); + assert.equal(status.GITEA_TOKEN, false); + }); + + it('describes a change without revealing the secret', () => { + const diff = diffValues( + { DISCORD_TOKEN: 'avant', WEB_PORT: '3080' }, + { DISCORD_TOKEN: 'apres', WEB_PORT: '4000' }, + ); + const token = diff.find((entry) => entry.key === 'DISCORD_TOKEN'); + + assert.equal(token.before, '••••••'); + assert.equal(token.after, '••••••'); + assert.equal(token.restartRequired, true); + + const port = diff.find((entry) => entry.key === 'WEB_PORT'); + assert.equal(port.after, '4000'); + }); +}); diff --git a/tests/web-deployments.test.js b/tests/web-deployments.test.js new file mode 100644 index 0000000..71a0105 --- /dev/null +++ b/tests/web-deployments.test.js @@ -0,0 +1,224 @@ +import assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { createServer } from 'node:http'; +import { after, afterEach, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + countByStatus, + createTarget, + getTarget, + listAutoTargets, + listDeployments, + listTargets, + removeTarget, + updateTarget, +} from '../src/database/repositories/deploy-repository.js'; +import { splitRepository } from '../src/services/gitea/gitea-admin.js'; +import { assertRunnable, describeTarget, runDeployment } from '../src/web/services/deploy-service.js'; + +const GUILD = 'guild-1'; + +const webhookTarget = (overrides = {}) => + createTarget({ + guildId: GUILD, + name: 'production', + repository: 'FWS/FWS-Arch', + environment: 'production', + kind: 'webhook', + config: { url: 'http://127.0.0.1:1/hook', secret: 'partage' }, + ...overrides, + }); + +describe('deploy repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('stores and reads back a target with its parsed config', () => { + const target = webhookTarget(); + assert.equal(target.config.url, 'http://127.0.0.1:1/hook'); + assert.equal(target.enabled, true); + assert.equal(target.auto_deploy, false); + assert.deepEqual(getTarget(target.id), target); + }); + + it('filters targets by repository', () => { + webhookTarget(); + webhookTarget({ name: 'site', repository: 'FWS/site' }); + + assert.equal(listTargets({ guildId: GUILD }).length, 2); + assert.equal(listTargets({ guildId: GUILD, repository: 'FWS/site' }).length, 1); + }); + + it('only returns enabled auto-deploy targets', () => { + webhookTarget({ name: 'manuel' }); + webhookTarget({ name: 'auto', autoDeploy: true }); + webhookTarget({ name: 'auto-en-pause', autoDeploy: true, enabled: false }); + + const auto = listAutoTargets({ guildId: GUILD, repository: 'FWS/FWS-Arch' }); + assert.deepEqual( + auto.map((target) => target.name), + ['auto'], + ); + }); + + it('updates only the known columns', () => { + const target = webhookTarget(); + // The repository speaks in column names; the API layer does the translation. + const updated = updateTarget(target.id, { environment: 'staging', bogus: 'ignoré', auto_deploy: true }); + + assert.equal(updated.environment, 'staging'); + assert.equal(updated.auto_deploy, true); + assert.equal(updated.bogus, undefined); + assert.ok(updated.updated_at); + }); + + it('keeps the history when its target is deleted', async () => { + const target = webhookTarget(); + await runDeployment(null, target, { ref: 'main' }).catch(() => null); + removeTarget(target.id); + + const [deployment] = listDeployments({ guildId: GUILD }); + assert.equal(deployment.target_id, null); + assert.equal(deployment.target_name, 'production'); + }); + + it('describes a target in one line', () => { + assert.match(describeTarget(webhookTarget()), /^POST http/); + assert.equal( + describeTarget({ kind: 'gitea-action', config: { workflow: 'deploy.yml', ref: 'main' } }), + 'workflow deploy.yml sur main', + ); + }); +}); + +describe('deploy guards', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses a disabled target', () => { + assert.throws(() => assertRunnable(webhookTarget({ enabled: false })), { status: 400 }); + }); + + it('refuses a webhook target with no url', () => { + assert.throws(() => assertRunnable(webhookTarget({ config: {} })), { status: 400 }); + }); + + it('refuses a command target while command deploys are off', () => { + const target = webhookTarget({ name: 'shell', kind: 'command', config: { command: 'echo bonjour' } }); + // `WEB_ALLOW_COMMAND_DEPLOYS` is unset in the tests, so this must be blocked. + assert.throws(() => assertRunnable(target), { status: 403 }); + }); + + it('refuses an unknown kind', () => { + assert.throws(() => assertRunnable({ enabled: true, kind: 'magic', config: {} }), { status: 400 }); + }); +}); + +describe('webhook deployments', () => { + let server; + let received; + let reply; + + before(async () => { + initDatabase(':memory:'); + server = createServer((request, response) => { + let body = ''; + request.on('data', (chunk) => (body += chunk)); + request.on('end', () => { + received = { headers: request.headers, body }; + response.writeHead(reply.status, { 'Content-Type': 'text/plain' }).end(reply.body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + }); + + after(async () => { + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => { + getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'); + received = null; + reply = { status: 200, body: 'déployé' }; + }); + afterEach(() => { + received = null; + }); + + const url = () => `http://127.0.0.1:${server.address().port}/hook`; + + it('calls the webhook and records a success', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + const deployment = await runDeployment(null, target, { releaseTag: 'v1.0.0', triggeredBy: 'u1' }); + + assert.equal(deployment.status, 'success'); + assert.match(deployment.log, /déployé/); + + const [stored] = listDeployments({ guildId: 'guild-1' }); + assert.equal(stored.status, 'success'); + assert.equal(stored.release_tag, 'v1.0.0'); + assert.ok(stored.finished_at); + }); + + it('signs the payload with the shared secret', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + await runDeployment(null, target, { ref: 'main' }); + + const expected = createHmac('sha256', 'partage').update(received.body).digest('hex'); + assert.equal(received.headers['x-fws-signature'], expected); + }); + + it('sends the deployment context in the body', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, { releaseTag: 'v2.0.0', ref: 'main', triggeredBy: 'u9' }); + + const payload = JSON.parse(received.body); + assert.equal(payload.repository, 'FWS/FWS-Arch'); + assert.equal(payload.environment, 'production'); + assert.equal(payload.releaseTag, 'v2.0.0'); + assert.equal(payload.triggeredBy, 'u9'); + }); + + it('omits the signature when no secret is configured', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, {}); + assert.equal(received.headers['x-fws-signature'], undefined); + }); + + it('records a failure when the endpoint answers with an error', async () => { + reply = { status: 500, body: 'boum' }; + const target = webhookTarget({ config: { url: url() } }); + const deployment = await runDeployment(null, target, {}); + + assert.equal(deployment.status, 'failed'); + assert.match(deployment.error, /500/); + assert.match(deployment.log, /boum/); + }); + + it('counts the deployments by status', async () => { + const ok = webhookTarget({ name: 'ok', config: { url: url() } }); + await runDeployment(null, ok, {}); + reply = { status: 503, body: '' }; + await runDeployment(null, ok, {}); + + const counts = Object.fromEntries(countByStatus('guild-1').map((row) => [row.status, row.count])); + assert.equal(counts.success, 1); + assert.equal(counts.failed, 1); + }); +}); + +describe('repository names', () => { + it('splits a full name', () => { + assert.deepEqual(splitRepository('FWS/FWS-Arch'), { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('rejects anything that is not exactly owner/repo', () => { + assert.equal(splitRepository('FWS'), null); + assert.equal(splitRepository('FWS/Arch/extra'), null); + assert.equal(splitRepository(''), null); + assert.equal(splitRepository(undefined), null); + }); +}); diff --git a/tests/web-router.test.js b/tests/web-router.test.js new file mode 100644 index 0000000..3b75ed5 --- /dev/null +++ b/tests/web-router.test.js @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { createRouter } from '../src/web/router.js'; + +const noop = () => null; + +describe('web router', () => { + const router = createRouter(); + router.get('/api/health', noop, { public: true }); + router.get('/api/repositories/:owner/:repo', noop); + router.post('/api/repositories/:owner/:repo/issues', noop); + router.delete('/api/repositories/:owner/:repo/branches', noop); + + it('matches a static route', () => { + const route = router.resolve('GET', '/api/health'); + assert.deepEqual(route.params, {}); + assert.equal(route.options.public, true); + }); + + it('extracts named parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/FWS-Arch'); + assert.deepEqual(route.params, { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('decodes percent-encoded parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/mon%20depot'); + assert.equal(route.params.repo, 'mon depot'); + }); + + it('keeps methods apart on the same path', () => { + assert.doesNotThrow(() => router.resolve('DELETE', '/api/repositories/FWS/Arch/branches')); + assert.throws(() => router.resolve('GET', '/api/repositories/FWS/Arch/branches'), { status: 405 }); + }); + + it('rejects an unknown path with 404', () => { + assert.throws(() => router.resolve('GET', '/api/nope'), { status: 404 }); + }); + + it('does not let a shorter path match a longer pattern', () => { + assert.throws(() => router.resolve('GET', '/api/repositories/FWS'), { status: 404 }); + }); + + it('lists the registered routes', () => { + assert.ok(router.list().includes('POST /api/repositories/:owner/:repo/issues')); + }); +}); diff --git a/tests/web-server.test.js b/tests/web-server.test.js new file mode 100644 index 0000000..c49eb42 --- /dev/null +++ b/tests/web-server.test.js @@ -0,0 +1,179 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, describe, it } from 'node:test'; +import { closeDatabase, initDatabase } from '../src/database/index.js'; +import { createHandler } from '../src/web/server.js'; +import { generateRuntimeSetupToken } from '../src/web/setup-state.js'; + +/** Drives the real request handler over a loopback socket (M16-T01). */ +function serve(options) { + const server = createServer(createHandler(options)); + const ready = new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + + return { + ready, + close: () => new Promise((resolve) => server.close(resolve)), + url: (path) => `http://127.0.0.1:${server.address().port}${path}`, + fetch: (path, init) => fetch(`http://127.0.0.1:${server.address().port}${path}`, init), + }; +} + +const WRITE_HEADERS = { 'Content-Type': 'application/json', 'X-Requested-With': 'fws-dashboard' }; + +describe('dashboard server', () => { + let app; + + before(async () => { + initDatabase(':memory:'); + app = serve({ client: null, setupOnly: false }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('answers the health probe without a session', async () => { + const response = await app.fetch('/api/health'); + const body = await response.json(); + + assert.equal(response.status, 200); + assert.equal(body.status, 'starting'); + assert.equal(body.setupOnly, false); + }); + + it('describes how to sign in without a session', async () => { + const body = await app.fetch('/api/auth/config').then((response) => response.json()); + assert.equal(typeof body.oauthConfigured, 'boolean'); + assert.equal(body.loginUrl, '/auth/login'); + }); + + it('reports an anonymous visitor as not authenticated', async () => { + const body = await app.fetch('/api/me').then((response) => response.json()); + assert.equal(body.authenticated, false); + }); + + it('refuses a protected route with 401', async () => { + const response = await app.fetch('/api/overview'); + assert.equal(response.status, 401); + assert.match((await response.json()).error, /Authentification/); + }); + + it('returns 404 on an unknown API route', async () => { + assert.equal((await app.fetch('/api/nope')).status, 404); + }); + + it('returns 405 when the path exists under another method', async () => { + const response = await app.fetch('/api/health', { method: 'POST', headers: WRITE_HEADERS, body: '{}' }); + assert.equal(response.status, 405); + }); + + it('blocks a write that does not carry the dashboard header', async () => { + const response = await app.fetch('/api/auth/logout', { method: 'POST' }); + assert.equal(response.status, 403); + assert.match((await response.json()).error, /X-Requested-With/); + }); + + it('serves the single page application shell', async () => { + const response = await app.fetch('/'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/html/); + assert.match(body, /
    { + const response = await app.fetch('/repos/FWS/FWS-Arch'); + assert.equal(response.status, 200); + assert.match(await response.text(), /
    { + const response = await app.fetch('/core/dom.js'); + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /javascript/); + }); + + it('sends the security headers on every response', async () => { + const response = await app.fetch('/'); + assert.equal(response.headers.get('x-frame-options'), 'DENY'); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + assert.match(response.headers.get('content-security-policy'), /frame-ancestors 'none'/); + }); + + it('never serves a file outside the public directory', async () => { + // The path is normalised server side, so the traversal lands on the shell. + const response = await app.fetch('/..%2f..%2fpackage.json'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.doesNotMatch(body, /"fws-discordbot"/); + }); + + it('rejects a malformed JSON body', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: 'pas du json', + }); + assert.equal(response.status, 400); + }); +}); + +describe('bootstrap mode', () => { + let app; + let token; + + before(async () => { + initDatabase(':memory:'); + token = generateRuntimeSetupToken(); + app = serve({ client: null, setupOnly: true }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('announces itself as a setup-only server', async () => { + const body = await app.fetch('/api/health').then((response) => response.json()); + assert.equal(body.setupOnly, true); + }); + + it('does not even register the dashboard routes', async () => { + assert.equal((await app.fetch('/api/overview')).status, 404); + assert.equal((await app.fetch('/api/settings')).status, 404); + }); + + it('refuses a wrong bootstrap token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token: 'mauvais' }), + }); + assert.equal(response.status, 403); + }); + + it('opens a confined session with the right token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token }), + }); + assert.equal(response.status, 200); + + const cookie = response.headers.getSetCookie()[0].split(';')[0]; + const me = await app.fetch('/api/me', { headers: { cookie } }).then((r) => r.json()); + assert.equal(me.source, 'setup'); + + const configuration = await app.fetch('/api/configuration', { headers: { cookie } }); + assert.equal(configuration.status, 200); + assert.ok((await configuration.json()).sections.length > 0); + }); + + it('serves the wizard front-end', async () => { + const response = await app.fetch('/views/setup.js'); + assert.equal(response.status, 200); + }); +}); From e63d6aa18eb48ebe2ffcb8c99baf772e94764b0d Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:52 +0200 Subject: [PATCH 11/51] docs(web): document the dashboard and the configuration wizard Both READMEs gain the same section and the same variables, as the organisation requires them to stay in sync. Co-Authored-By: Claude Opus 5 (1M context) --- README.en.md | 90 +++++++++++++++---- README.md | 95 ++++++++++++++++---- docs/architecture.md | 26 +++++- docs/web-dashboard.md | 197 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 376 insertions(+), 32 deletions(-) create mode 100644 docs/web-dashboard.md diff --git a/README.en.md b/README.en.md index ea7fd09..bb436fd 100644 --- a/README.en.md +++ b/README.en.md @@ -161,6 +161,23 @@ Full template: [`.env.example`](.env.example). Default values in brackets. | `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea | | `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks | +### Web dashboard + +| Variable | Default | Description | +| --- | --- | --- | +| `WEB_ENABLED` | `false` | Serves the admin site from the bot process | +| `WEB_HOST` | `127.0.0.1` | Listening interface. Use `0.0.0.0` only behind an HTTPS reverse proxy | +| `WEB_PORT` | `3080` | Site port. When it equals `WEBHOOK_PORT`, a single HTTP server is started | +| `WEB_PUBLIC_URL` | — | Public URL of the site, base of the OAuth2 `/auth/callback` redirect | +| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret | +| `WEB_SESSION_SECRET` | — | Session signing key (64 hexadecimal characters) | +| `WEB_SESSION_TTL_HOURS` | `12` | Session lifetime before signing in again | +| `WEB_SETUP_TOKEN` | — | Bootstrap token opening the wizard without a Discord account | +| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Allows shell-command deploy targets (Owner only) | +| `WEB_ALLOW_RESTART` | `false` | Shows the bot restart button | +| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Delay after which a deployment is marked failed | +| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | API requests per minute and per IP address | + ### SQLite and links | Variable | Default | Description | @@ -299,7 +316,43 @@ Every command checks the FWS level **and** the matching Discord permission. The Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message. -## 6. Automations +## 6. Web dashboard + +The bot serves its own admin site: Gitea organization, repositories, releases, deployments, Discord server, logs and configuration. Full details: [`docs/web-dashboard.md`](docs/web-dashboard.md). + +No added dependency: `node:http` for the server, `node:sqlite` for the sessions, and a plain JavaScript front-end served as is. + +### 6.1 Getting started + +Without a `.env` the bot refuses to start, so the configuration wizard runs on its own, without connecting to Discord. + +```bash +npm run setup +``` + +The console prints the site URL and a temporary bootstrap token. Once the file is written, set `WEB_ENABLED=true` and start the bot as usual: the site then listens on `WEB_HOST:WEB_PORT`. + +So that members can sign in with Discord: copy the **Client Secret** from the portal into `DISCORD_CLIENT_SECRET`, add `/auth/callback` under **OAuth2 → Redirects** exactly as is, and generate `WEB_SESSION_SECRET`. + +### 6.2 Access and display modes + +The site reuses the access levels of the slash commands, derived from the Discord roles. Signing in requires at least the **Staff** level; **Dev** unlocks writes on repositories and deployments; **Owner** unlocks repository deletion, API tokens, backups and configuration. + +A **Simple / Advanced** switch hides or reveals the technical panels. It changes no permission: every call is checked again on the server. + +### 6.3 Configuration wizard + +Every `.env` variable is described once, in `src/web/services/env-schema.js`: the form, the explanations, the validation and the generated file all derive from it. + +The wizard tells you where to find each value, validates as you type, flags questionable combinations, generates the secrets, tests the Discord token and the Gitea token **before** writing anything, shows a preview of the file, backs the previous one up as `.env.bak-` then writes the new one with `600` permissions. An empty secret keeps the value already in place. + +### 6.4 Releases and deployments + +Publishing a release from the site builds its notes from the Conventional Commits, announces it in the releases channel and triggers the targets marked for automatic deployment. + +Three kinds of target: an HMAC-SHA256 signed **webhook** (recommended, nothing runs on the bot host), a **Gitea Actions workflow**, and a **shell command** — the latter stays blocked until `WEB_ALLOW_COMMAND_DEPLOYS` is enabled, and requires the Owner level. Every attempt leaves its full log in the history, successful or not. + +## 7. Automations - **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed). - **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age. @@ -309,7 +362,7 @@ Legend: ✅ working · expected errors are returned as ephemeral messages (`User - **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status. - **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call. -## 7. Architecture +## 8. Architecture Full details: [`docs/architecture.md`](docs/architecture.md). @@ -333,6 +386,9 @@ src/ │ └── voice/ # voice-service.js (several triggers, temporary channels, panel) ├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/ ├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── web/ # Dashboard: server.js · router.js · http.js +│ # auth/ (Discord OAuth2, sessions, access control) · api/ (one module per domain) +│ # services/ (.env schema, deployments) · public/ (front-end, no build) ├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls) └── utils/ # retry.js (exponential backoff) · cooldown.js ``` @@ -361,23 +417,23 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui - Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`. - Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**. -## 8. Database (SQLite) +## 9. Database (SQLite) - Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled. - Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`). -- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`. -- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — SQL queries never leave that layer. -- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) and `005-bot-statuses.sql` (bot statuses edited from a command) complete the initial schema. +- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`, `web_sessions` (dashboard sessions, cookie fingerprint only), `web_api_tokens`, `deploy_targets` (deploy targets), `deployments` (history and log of every run). +- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — SQL queries never leave that layer. +- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) `005-bot-statuses.sql` (bot statuses edited from a command) and `006-web-dashboard.sql` (sessions, API tokens, deploy targets and history) complete the initial schema. - The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`). -## 9. Logs +## 10. Logs - **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console. - Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr. - **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line. - Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`). -## 10. npm scripts +## 11. npm scripts | Script | Purpose | | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -387,13 +443,13 @@ Every text shown in Discord follows the same rules, listed at the top of `src/ui | `npm run db:init` | Creates the SQLite database and applies the migrations | | `npm run lint` / `npm run lint:fix` | ESLint (check / fix) | | `npm run format` / `npm run format:check` | Prettier (format / check) | -| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §12) | +| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §13) | | `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date | -| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | +| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` | When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels. -## 11. Security +## 12. Security - Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted. - No action is possible on a role or member positioned above the caller. @@ -402,14 +458,14 @@ When something goes wrong: run `npm run deploy:commands` after any command chang - Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only). - User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option). -## 12. Versioning and releases +## 13. Versioning and releases - **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states). - **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date. - Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`. - Generating it is part of the definition of done: the file is never edited by hand. -## 13. Contributing +## 14. Contributing The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here: @@ -441,7 +497,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it. - Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions. -## 14. Production checklist +## 15. Production checklist - [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention) - [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_) @@ -452,6 +508,9 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion - [ ] Enable the **Server Members** intent in the developer portal - [ ] Configure Gitea: least privilege token + webhook with a secret +- [ ] Configure the dashboard: `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` and the OAuth2 redirect declared in the portal +- [ ] Put an HTTPS reverse proxy in front of the site, then clear `WEB_SETUP_TOKEN` +- [ ] Declare the deploy targets and run a test deployment - [ ] Protect and back up the SQLite database - [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook - [ ] Test the API limits and the error paths @@ -459,7 +518,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - [ ] Fill in the official links and the screenshots (`assets/screenshots/`) - [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`) -## 15. Resources +## 16. Resources - FWS organisation: `[link to add]` - FWS Discord server: `[link to add]` @@ -467,6 +526,7 @@ The rules shared by every FWS repository live in the [organisation `.profile`](h - Gitea instance: `[link to add]` - FWS documentation: `[link to add]` - Technical documentation: [`docs/architecture.md`](docs/architecture.md) +- Web dashboard: [`docs/web-dashboard.md`](docs/web-dashboard.md) - Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md) - Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_ - Instructions for AI agents: [`AGENTS.md`](AGENTS.md) diff --git a/README.md b/README.md index 1aca567..51c1654 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Choix assumés : **une seule dépendance runtime** (discord.js), aucun module na | **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks | | **`node:test`** | — | Tests unitaires intégrés (`node --test`) | | **ESLint** | ^9.30.0 (flat config) | Lint | +| **Front du tableau de bord** | — | JavaScript natif servi tel quel, aucune étape de build | + | **Prettier** | ^3.6.2 | Format | ## 2. Prérequis @@ -161,6 +163,23 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare | `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea | | `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks | +### Tableau de bord web + +| Variable | Défaut | Description | +| --- | --- | --- | +| `WEB_ENABLED` | `false` | Sert le site d'administration depuis le processus du bot | +| `WEB_HOST` | `127.0.0.1` | Interface d'écoute. `0.0.0.0` uniquement derrière un reverse proxy HTTPS | +| `WEB_PORT` | `3080` | Port du site. S'il vaut `WEBHOOK_PORT`, un seul serveur HTTP est démarré | +| `WEB_PUBLIC_URL` | — | URL publique du site, base de la redirection OAuth2 `/auth/callback` | +| `DISCORD_CLIENT_SECRET` | — | Developer Portal → OAuth2 → Client Secret | +| `WEB_SESSION_SECRET` | — | Clé de signature des sessions (64 caractères hexadécimaux) | +| `WEB_SESSION_TTL_HOURS` | `12` | Durée d'une session avant reconnexion | +| `WEB_SETUP_TOKEN` | — | Jeton d'amorçage ouvrant l'assistant sans compte Discord | +| `WEB_ALLOW_COMMAND_DEPLOYS` | `false` | Autorise les cibles de déploiement de type commande shell (Owner) | +| `WEB_ALLOW_RESTART` | `false` | Affiche le bouton de redémarrage du bot | +| `WEB_DEPLOY_TIMEOUT_MS` | `900000` | Délai au-delà duquel un déploiement est en échec | +| `WEB_RATE_LIMIT_PER_MINUTE` | `240` | Requêtes API par minute et par adresse IP | + ### SQLite et liens | Variable | Défaut | Description | @@ -299,7 +318,43 @@ Chaque commande vérifie le niveau FWS **et** la permission Discord correspondan Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique. -## 6. Automatisations +## 6. Tableau de bord web + +Le bot sert son propre site d'administration : organisation Gitea, dépôts, releases, déploiements, serveur Discord, journaux et configuration. Détail complet : [`docs/web-dashboard.md`](docs/web-dashboard.md). + +Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour les sessions, et un front en JavaScript natif servi tel quel. + +### 6.1 Démarrer + +Sans `.env`, le bot refuse de démarrer : l'assistant de configuration se lance donc seul, sans connexion à Discord. + +```bash +npm run setup +``` + +La console affiche l'URL du site et un jeton d'amorçage temporaire. Une fois le fichier écrit, mets `WEB_ENABLED=true` et démarre le bot normalement : le site écoute alors sur `WEB_HOST:WEB_PORT`. + +Pour que les membres puissent se connecter avec Discord : copie le **Client Secret** du portail dans `DISCORD_CLIENT_SECRET`, ajoute `/auth/callback` dans **OAuth2 → Redirects** à l'identique, et génère `WEB_SESSION_SECRET`. + +### 6.2 Accès et modes d'affichage + +Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff** ; **Dev** ouvre l'écriture sur les dépôts et les déploiements ; **Owner** ouvre la suppression de dépôt, les jetons d'API, les sauvegardes et la configuration. + +Un commutateur **Simple / Avancé** masque ou révèle les panneaux techniques. Il ne change aucun droit : chaque appel est revérifié côté serveur. + +### 6.3 Assistant de configuration + +Chaque variable du `.env` est décrite une seule fois, dans `src/web/services/env-schema.js` : le formulaire, les explications, la validation et le fichier généré en découlent tous. + +L'assistant indique où trouver chaque valeur, valide au fil de la frappe, signale les combinaisons douteuses, génère les secrets, teste le token Discord et le jeton Gitea **avant** d'écrire, montre un aperçu du fichier, sauvegarde l'ancien en `.env.bak-` puis écrit le nouveau avec les permissions `600`. Un secret laissé vide conserve la valeur déjà en place. + +### 6.4 Releases et déploiements + +Publier une release depuis le site génère ses notes à partir des commits Conventional Commits, l'annonce dans le salon des releases et déclenche les cibles marquées en déploiement automatique. + +Trois types de cible : **webhook** signé en HMAC-SHA256 (recommandé, rien ne s'exécute sur la machine du bot), **workflow Gitea Actions**, et **commande shell** — cette dernière reste bloquée tant que `WEB_ALLOW_COMMAND_DEPLOYS` n'est pas activé, et demande le niveau Owner. Chaque tentative laisse son journal complet dans l'historique, réussie comme échouée. + +## 7. Automatisations - **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés). - **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte. @@ -309,7 +364,7 @@ Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message - **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé. - **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API. -## 7. Architecture +## 8. Architecture Détails complets : [`docs/architecture.md`](docs/architecture.md). @@ -333,6 +388,9 @@ src/ │ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau) ├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/ ├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── web/ # Tableau de bord : server.js · router.js · http.js +│ # auth/ (OAuth2 Discord, sessions, contrôle d'accès) · api/ (un module par domaine) +│ # services/ (schéma du .env, déploiements) · public/ (front, sans build) ├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages) └── utils/ # retry.js (backoff exponentiel) · cooldown.js ``` @@ -361,55 +419,58 @@ Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en - Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`. - Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal. -## 8. Base de données (SQLite) +## 9. Base de données (SQLite) - Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées. - Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`). -- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`. -- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. -- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) et `005-bot-statuses.sql` (statuts du bot édités en commande) complètent le schéma initial. +- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`, `web_sessions` (sessions du tableau de bord, empreinte du cookie seulement), `web_api_tokens`, `deploy_targets` (cibles de déploiement), `deployments` (historique et journal de chaque exécution). +- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-`, `web-session-`, `deploy-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. +- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) `005-bot-statuses.sql` (statuts du bot édités en commande) et `006-web-dashboard.sql` (sessions, jetons d'API, cibles et historique de déploiement) complètent le schéma initial. - La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`). -## 9. Logs +## 10. Logs - Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console. - Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr. - **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée. - Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`). -## 10. Scripts npm +## 11. Scripts npm | Script | Rôle | | --- | --- | | `npm start` | Démarre le bot (`node src/index.js`) | | `npm run dev` | Démarre avec rechargement automatique (`node --watch`) | +| `npm run setup` | Lance l'assistant de configuration du `.env`, sans connexion Discord | | `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) | | `npm run db:init` | Crée la base SQLite et applique les migrations | | `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) | | `npm run format` / `npm run format:check` | Prettier (formater / vérifier) | -| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §12) | +| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §13) | | `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) | -| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | +| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs`, `web-router`, `web-configuration`, `web-auth`, `web-deployments`, `web-server` | En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles. -## 11. Sécurité +## 12. Sécurité - Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client. - Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur. - Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique). - Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery. - Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement). +- Tableau de bord : connexion Discord obligatoire (niveau Staff minimum), session en cookie `HttpOnly` dont seule l'empreinte est stockée, en-tête `X-Requested-With` exigé sur chaque écriture, vérification de l'origine, CSP restreinte à `self`, limitation de débit par adresse IP. +- Le site écoute sur `127.0.0.1` par défaut : place un reverse proxy HTTPS devant lui avant toute exposition. Les déploiements par commande shell et le redémarrage restent désactivés tant qu'on ne les active pas explicitement. - Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options). -## 12. Versionnage et releases +## 13. Versionnage et releases - **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer). - **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour. - Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`. - La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main. -## 13. Contribution +## 14. Contribution Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici : @@ -441,7 +502,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie. - Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions. -## 14. Checklist de mise en production +## 15. Checklist de mise en production - [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation) - [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*) @@ -452,6 +513,9 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - [ ] Configurer chaque salon vocal déclencheur (`/voice setup`) et vérifier création/suppression automatique - [ ] Activer l'intent **Server Members** dans le portail développeur - [ ] Configurer Gitea : token à moindre privilège + webhook avec secret +- [ ] Configurer le tableau de bord : `WEB_PUBLIC_URL`, `DISCORD_CLIENT_SECRET`, `WEB_SESSION_SECRET` et la redirection OAuth2 déclarée dans le portail +- [ ] Placer un reverse proxy HTTPS devant le site, puis vider `WEB_SETUP_TOKEN` +- [ ] Déclarer les cibles de déploiement et lancer un déploiement de test - [ ] Protéger et sauvegarder la base SQLite - [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea - [ ] Tester les limites API et les chemins d'erreur @@ -459,7 +523,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`) - [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`) -## 15. Ressources +## 16. Ressources - Organisation FWS : `[lien à ajouter]` - Serveur Discord FWS : `[lien à ajouter]` @@ -467,6 +531,7 @@ Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de - Instance Gitea : `[lien à ajouter]` - Documentation FWS : `[lien à ajouter]` - Documentation technique : [`docs/architecture.md`](docs/architecture.md) +- Tableau de bord web : [`docs/web-dashboard.md`](docs/web-dashboard.md) - Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) - Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)* - Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md) diff --git a/docs/architecture.md b/docs/architecture.md index bb48862..289be66 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,7 +13,8 @@ fws-discordbot/ ├── logs/ # Logs techniques journaliers (ignoré par git) ├── scripts/ │ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur -│ └── init-database.js # Crée la base et applique les migrations +│ ├── init-database.js # Crée la base et applique les migrations +│ └── setup-server.js # Assistant de configuration du .env, sans Discord ├── src/ │ ├── index.js # Point d'entrée │ ├── config/ @@ -34,6 +35,13 @@ fws-discordbot/ │ │ ├── migrations/ # Fichiers SQL numérotés │ │ └── repositories/ # Accès aux tables │ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea +│ ├── web/ # Tableau de bord : serveur, API, front (voir web-dashboard.md) +│ │ ├── server.js # Serveur HTTP, répartition et erreurs +│ │ ├── router.js # Routeur minimal `/api/x/:param` +│ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès +│ │ ├── api/ # Un module par domaine exposé +│ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements +│ │ └── public/ # Front JavaScript natif, servi tel quel │ ├── ui/ # Embeds et boutons standardisés │ └── utils/ # Retry, cooldown… └── tests/ # Tests node:test @@ -58,6 +66,20 @@ export const once = false; // optionnel export async function execute(client, ...args) {} ``` +## Tableau de bord web + +Le bot sert un site d'administration (organisation, dépôts, releases, déploiements, configuration). Il réutilise les niveaux d'accès des commandes, déduits des rôles Discord, et ne démarre que si `WEB_ENABLED=true`. + +Aucune dépendance ajoutée : `node:http`, `node:sqlite`, `node:crypto`, et un front sans étape de build. Quand `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP sert le site et la route des webhooks. + +Une route se déclare avec son niveau minimum, appliqué par le serveur avant l'appel : + +```js +router.get('/api/repositories/:owner/:repo', handler, { access: ACCESS_LEVELS.STAFF }); +``` + +Détail complet : [`web-dashboard.md`](web-dashboard.md). + ## Intents Discord | Intent | Usage | Privilégié | @@ -73,7 +95,7 @@ export async function execute(client, ...args) {} ```bash npm install -cp .env.example .env # puis remplir les valeurs +npm run setup # assistant de configuration du .env, ou copier .env.example à la main npm run db:init npm run deploy:commands npm run dev diff --git a/docs/web-dashboard.md b/docs/web-dashboard.md new file mode 100644 index 0000000..f2e27de --- /dev/null +++ b/docs/web-dashboard.md @@ -0,0 +1,197 @@ +# Tableau de bord web + +Le bot sert lui-même un site d'administration : pilotage de l'organisation Gitea et de ses dépôts, gestion du serveur Discord, pipeline de releases et de déploiements, et un assistant qui écrit le fichier `.env` pas à pas. + +Aucune dépendance supplémentaire : `node:http` pour le serveur, `node:sqlite` pour les sessions, `node:crypto` pour les signatures, et un front en JavaScript natif servi tel quel (pas d'étape de build). + +## 1. Démarrer + +### Première installation, sans `.env` + +Le bot refuse de démarrer sans `DISCORD_TOKEN`. L'assistant de configuration se lance donc seul : + +```bash +npm install +npm run setup +``` + +La console affiche l'URL et un jeton d'amorçage à usage unique. Ouvre l'URL, colle le jeton, déroule l'assistant, enregistre. Puis : + +```bash +npm run db:init +npm run deploy:commands +npm run dev +``` + +### Site complet, bot configuré + +Mets `WEB_ENABLED=true` dans le `.env`, puis `npm start`. Le site écoute sur `WEB_HOST:WEB_PORT` (par défaut `127.0.0.1:3080`). + +Pour que les membres puissent se connecter avec Discord : + +1. Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`. +2. Toujours dans **OAuth2 → Redirects**, ajoute `/auth/callback`, à l'identique. +3. Génère `WEB_SESSION_SECRET` (l'assistant a un bouton pour ça). + +## 2. Qui a accès à quoi + +Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff**. + +| Niveau | Peut | +| --------- | --------------------------------------------------------------------------------------------------------- | +| **Staff** | Tout consulter, créer des issues, commenter, modérer, clôturer des tickets, publier une annonce | +| **Dev** | En plus : modifier les dépôts, merger, gérer branches et releases, lancer un déploiement, gérer les rôles | +| **Owner** | En plus : supprimer un dépôt, gérer collaborateurs et webhooks, jetons d'API, sauvegardes, `.env` | + +Un membre sans rôle Staff, Dev ou Owner ne peut pas ouvrir le site. Le propriétaire du serveur Discord est toujours Owner. + +### Modes Simple et Avancé + +Le commutateur en bas de la barre latérale masque ou révèle les panneaux techniques (identifiants bruts, journaux, réglages fins, colonnes secondaires). Le mode est retenu par navigateur, et n'a aucun effet sur les droits réels : le serveur vérifie chaque appel de son côté. + +## 3. Les pages + +| Page | Contenu | +| ---------------------- | ----------------------------------------------------------------------------------------------- | +| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements | +| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt | +| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages | +| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés | +| **Déploiements** | Cibles de déploiement et historique complet, avec le journal de chaque exécution | +| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes | +| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot | +| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués | +| **Paramètres** | Comportement du bot, connexions, sessions, jetons d'API, maintenance | +| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré | + +## 4. Assistant de configuration + +Le fichier `src/web/services/env-schema.js` décrit **chaque** variable : libellé, explication, type, valeur par défaut, marche à suivre pour l'obtenir. L'assistant, la validation et le `.env` généré en découlent tous. Ajouter une variable au bot, c'est l'ajouter là et nulle part ailleurs. + +L'assistant : + +- explique chaque étape (où cliquer dans le Developer Portal, quelles portées cocher dans Gitea) ; +- valide au fil de la frappe et signale les combinaisons douteuses (webhooks sans secret, site exposé sans HTTPS) ; +- génère les secrets aléatoires sur demande ; +- teste le token Discord et le jeton Gitea **avant** d'écrire quoi que ce soit ; +- montre un aperçu du fichier et la liste des changements en attente ; +- sauvegarde l'ancien `.env` en `.env.bak-` puis écrit le nouveau en `chmod 600` ; +- conserve les variables qu'il ne connaît pas plutôt que de les perdre. + +Un secret laissé vide signifie « garde la valeur actuelle » : impossible d'effacer un token par inadvertance. Les secrets ne repartent jamais vers le navigateur — seul leur statut (renseigné ou non) est envoyé. + +Les valeurs du `.env` ne sont lues qu'au démarrage : l'assistant indique quelles modifications demandent un redémarrage. + +## 5. Releases et déploiements + +### Publier + +Depuis la page **Releases** : choisis le dépôt, le tag et la branche cible. Le bouton **Générer les notes** lit les commits depuis la release précédente et les regroupe comme `scripts/generate-changelog.js` : nouveautés, corrections, performance, autres changements, avec un bloc « changements incompatibles » pour les commits marqués `!` ou `BREAKING CHANGE`. + +Publier une release non brouillon annonce la version dans le salon `releases` et déclenche les cibles marquées « déploiement automatique ». + +### Cibles de déploiement + +| Type | Ce qui se passe | Risque | +| ----------------- | ----------------------------------------------------------------------- | ---------------------------------------- | +| **Webhook** | POST JSON signé HMAC-SHA256 vers ton serveur, en-tête `X-FWS-Signature` | Faible — rien ne s'exécute chez le bot | +| **Gitea Actions** | Déclenche un workflow `workflow_dispatch` | Faible | +| **Commande** | Exécute une commande shell sur la machine du bot | **Élevé** — exécution de code arbitraire | + +Les cibles « commande » sont doublement verrouillées : `WEB_ALLOW_COMMAND_DEPLOYS=true` **et** niveau Owner. Elles restent désactivées par défaut. + +Corps envoyé à un webhook : + +```json +{ + "deploymentId": 12, + "repository": "FWS/FWS-Arch", + "environment": "production", + "target": "production-web", + "ref": "main", + "releaseTag": "v1.2.0", + "triggeredBy": "123456789012345678", + "source": "web" +} +``` + +Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en hexadécimal, comparé en temps constant. + +Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec). + +## 6. Jetons d'API + +Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée. + +```bash +curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview +``` + +Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment. + +## 7. Sécurité + +- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site. +- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`. +- **Écritures.** Toute requête autre qu'une lecture exige l'en-tête `X-Requested-With: fws-dashboard`, que le navigateur ne peut pas forger depuis un autre site, plus une vérification de l'origine. +- **En-têtes.** CSP restreinte à `self`, `X-Frame-Options: DENY`, `nosniff`, aucune ressource tierce. +- **Limitation de débit.** `WEB_RATE_LIMIT_PER_MINUTE` requêtes par adresse IP et par minute. +- **Secrets.** Jamais renvoyés au navigateur, jamais écrits dans les logs (`maskSecrets`). +- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact. +- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur. + +## 8. Fonctionnement interne + +```text +src/web/ +├── server.js # Serveur HTTP, répartition, gestion des erreurs, limitation de débit +├── router.js # Routeur : motifs `/api/x/:param`, 404 et 405 +├── http.js # Réponses JSON, corps, cookies, fichiers statiques, en-têtes de sécurité +├── setup-state.js # Jeton d'amorçage de l'assistant +├── auth/ +│ ├── discord-oauth.js # Flux OAuth2 et calcul du niveau d'accès +│ ├── session.js # Sessions signées, jetons d'API, protection anti-CSRF +│ ├── guard.js # Contrôle d'accès par route +│ └── routes.js # /auth/login, /auth/callback, /api/me +├── api/ # Un module par domaine fonctionnel +├── services/ +│ ├── env-schema.js # Description documentée de chaque variable +│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env +│ └── deploy-service.js # Exécution des déploiements et notifications +└── public/ # Front servi tel quel (aucun build) + ├── index.html + ├── styles.css + ├── app.js # Shell, navigation, routage par fragment + ├── core/ # dom.js, api.js, ui.js + └── views/ # Une vue par page +``` + +Une route se déclare ainsi : + +```js +router.get( + '/api/repositories/:owner/:repo', + async ({ params, query, body, actor, context }) => { + return { fullName: `${params.owner}/${params.repo}` }; + }, + { access: ACCESS_LEVELS.STAFF }, +); +``` + +Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le corps JSON, puis sérialise la valeur retournée. Une `HttpError` fixe le code ; une `UserFacingError` devient un 400 ; toute autre erreur est journalisée et remplacée par un message générique. + +### Partage de port avec les webhooks + +Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port. + +## 9. Dépannage + +| Symptôme | Cause probable | +| ---------------------------------------------- | ------------------------------------------------------------------------------- | +| `state-mismatch` à la connexion | Cookies bloqués, ou plus de 10 minutes entre le clic et le retour | +| `exchange-failed` | L'URL de redirection du portail ne correspond pas exactement à `WEB_PUBLIC_URL` | +| `insufficient-level` | Le compte n'a ni rôle Staff, ni Dev, ni Owner sur le serveur | +| Déconnexion à chaque redémarrage | `WEB_SESSION_SECRET` n'est pas défini | +| « Gitea n'est pas configuré » | `GITEA_URL` ou `GITEA_TOKEN` manquant — teste le jeton depuis les paramètres | +| Onglet Actions vide | Gitea Actions désactivé sur le dépôt, ou Gitea antérieur à 1.20 | +| Les modifications du `.env` restent sans effet | Le fichier n'est lu qu'au démarrage : redémarre le bot | From 20ff7014307d3481bfce47c95d38edc691a4e572 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:12:44 +0200 Subject: [PATCH 12/51] fix(web): derive the OAuth2 redirect from the address actually used `WEB_PUBLIC_URL` was the only source of the `redirect_uri`, so a hosting panel or a proxy publishing the dashboard on another port produced a link Discord refuses, with nothing on screen pointing at the port mismatch. The browser's own origin is what Discord compares against, so the redirect now comes from the request, honouring `X-Forwarded-Host` and `X-Forwarded-Proto` when a proxy sits in front. `WEB_PUBLIC_URL` stays as the fallback for links built outside a request, and the sign-in page prints the exact value to declare in the portal. The `Secure` cookie flag follows the same rule: announcing HTTPS in the configuration while serving plain HTTP made the browser drop the session. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/api/settings.js | 4 +-- src/web/auth/discord-oauth.js | 45 ++++++++++++++++++++++++++++------ src/web/auth/routes.js | 23 +++++++++++------ src/web/auth/session.js | 35 ++++++++++++++++++++++---- src/web/public/views/login.js | 17 +++++++++++-- src/web/services/env-schema.js | 7 +++--- tests/web-auth.test.js | 37 +++++++++++++++++++++++++++- 7 files changed, 140 insertions(+), 28 deletions(-) diff --git a/src/web/api/settings.js b/src/web/api/settings.js index ae20c05..f1ab86a 100644 --- a/src/web/api/settings.js +++ b/src/web/api/settings.js @@ -99,7 +99,7 @@ const readManaged = () => export function registerSettingsRoutes(router) { router.get( '/api/settings', - ({ actor }) => ({ + ({ request, actor }) => ({ schema: MANAGED_SETTINGS, values: readManaged(), runtime: { @@ -144,7 +144,7 @@ export function registerSettingsRoutes(router) { publicUrl: env.web.publicUrl, sessionTtlHours: env.web.sessionTtlHours, oauthConfigured: isOauthConfigured(), - redirectUri: redirectUri(), + redirectUri: redirectUri(request), allowCommandDeploys: env.web.allowCommandDeploys, allowRestart: env.web.allowRestart, rateLimitPerMinute: env.web.rateLimitPerMinute, diff --git a/src/web/auth/discord-oauth.js b/src/web/auth/discord-oauth.js index bebce57..9223c1a 100644 --- a/src/web/auth/discord-oauth.js +++ b/src/web/auth/discord-oauth.js @@ -13,18 +13,46 @@ const DISCORD_API = 'https://discord.com/api/v10'; */ const SCOPES = ['identify', 'guilds.members.read']; -export const redirectUri = () => `${env.web.publicUrl}/auth/callback`; +/** + * Origin the visitor actually reached the dashboard on. + * + * It is the address in their browser bar that has to match the redirect + * declared in the Developer Portal, and a hosting panel or a proxy commonly + * publishes the site on a different port than `WEB_PUBLIC_URL` claims. + * Trusting the request rather than the configuration avoids a sign-in that + * fails on a port mismatch nobody thinks to look at. + */ +export function requestOrigin(request) { + const header = (name) => + String(request?.headers?.[name] ?? '') + .split(',')[0] + .trim(); -/** True when the OAuth2 login can actually run. */ -export function isOauthConfigured() { - return Boolean(env.discord.clientId && env.web.oauthClientSecret && env.web.publicUrl); + const host = header('x-forwarded-host') || header('host'); + if (!host) return env.web.publicUrl; + + const protocol = header('x-forwarded-proto') || (request.socket?.encrypted ? 'https' : 'http'); + return `${protocol}://${host}`; } -export function authorizeUrl(state) { +export const redirectUri = (request) => { + const origin = requestOrigin(request) || env.web.publicUrl; + return origin ? `${origin}/auth/callback` : ''; +}; + +/** + * True when the OAuth2 login can run. `WEB_PUBLIC_URL` is not required: the + * redirect is derived from the request when one is available. + */ +export function isOauthConfigured() { + return Boolean(env.discord.clientId && env.web.oauthClientSecret); +} + +export function authorizeUrl(state, request) { const params = new URLSearchParams({ client_id: env.discord.clientId, response_type: 'code', - redirect_uri: redirectUri(), + redirect_uri: redirectUri(request), scope: SCOPES.join(' '), state, prompt: 'none', @@ -45,13 +73,14 @@ async function discordFetch(endpoint, options = {}) { return response.status === 204 ? null : response.json(); } -export async function exchangeCode(code) { +/** Discord checks that this `redirect_uri` is the one used to obtain the code. */ +export async function exchangeCode(code, request) { const body = new URLSearchParams({ client_id: env.discord.clientId, client_secret: env.web.oauthClientSecret, grant_type: 'authorization_code', code, - redirect_uri: redirectUri(), + redirect_uri: redirectUri(request), }); return discordFetch('/oauth2/token', { diff --git a/src/web/auth/routes.js b/src/web/auth/routes.js index c8ed62c..8a7ceaa 100644 --- a/src/web/auth/routes.js +++ b/src/web/auth/routes.js @@ -12,6 +12,7 @@ import { fetchGuildMember, fetchUser, isOauthConfigured, + redirectUri, resolveAccessLevel, revokeToken, } from './discord-oauth.js'; @@ -23,26 +24,31 @@ const log = createLogger('web:auth'); export function registerAuthRoutes(router) { router.get( '/api/auth/config', - ({ context }) => ({ + ({ request, context }) => ({ oauthConfigured: isOauthConfigured(), setupAvailable: hasSetupToken(), setupOnly: context.setupOnly, guildConfigured: Boolean(env.discord.guildId), loginUrl: '/auth/login', + // Shown on the sign-in page: it is the value to declare in the portal. + redirectUri: redirectUri(request), }), { public: true }, ); router.get( '/auth/login', - ({ response }) => { + ({ request, response }) => { if (!isOauthConfigured()) { redirect(response, '/#/login?error=oauth-not-configured'); return; } const state = signState(randomBytes(16).toString('base64url')); - appendCookie(response, serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies() })); - redirect(response, authorizeUrl(state)); + appendCookie( + response, + serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies(request) }), + ); + redirect(response, authorizeUrl(state, request)); }, { public: true }, ); @@ -56,7 +62,10 @@ export function registerAuthRoutes(router) { const state = query.get('state'); const expected = parseCookies(request.headers.cookie)[STATE_COOKIE]; - appendCookie(response, serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies() })); + appendCookie( + response, + serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies(request) }), + ); if (!state || state !== expected || !verifyState(state)) return failure('state-mismatch'); const code = query.get('code'); @@ -64,9 +73,9 @@ export function registerAuthRoutes(router) { let grant; try { - grant = await exchangeCode(code); + grant = await exchangeCode(code, request); } catch (error) { - log.warn('OAuth2 code exchange failed', error); + log.warn('OAuth2 code exchange failed', { error, redirectUri: redirectUri(request) }); return failure('exchange-failed'); } diff --git a/src/web/auth/session.js b/src/web/auth/session.js index 4782d00..1e47550 100644 --- a/src/web/auth/session.js +++ b/src/web/auth/session.js @@ -30,7 +30,19 @@ const pepper = (() => { const hash = (value) => createHmac('sha256', pepper).update(value).digest('hex'); -export const secureCookies = () => env.web.publicUrl.startsWith('https://'); +/** + * A `Secure` cookie is dropped by the browser over plain HTTP, so the flag has + * to follow the scheme the visitor actually used rather than what the + * configuration announces. + */ +export const secureCookies = (request) => { + const forwarded = String(request?.headers?.['x-forwarded-proto'] ?? '') + .split(',')[0] + .trim(); + if (forwarded) return forwarded === 'https'; + if (request?.socket?.encrypted) return true; + return env.web.publicUrl.startsWith('https://'); +}; export function issueToken() { return randomBytes(32).toString('base64url'); @@ -74,7 +86,7 @@ export function openSession(request, response, { user = {}, accessLevel, source appendCookie( response, - serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies() }), + serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies(request) }), ); log.info('Dashboard session opened', { userId: session.user_id, source, accessLevel }); return session; @@ -84,7 +96,7 @@ export function closeSession(request, response) { const token = parseCookies(request.headers.cookie)[SESSION_COOKIE]; const session = token ? getLiveSessionByHash(hash(token)) : null; if (session) deleteSession(session.id); - appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies() })); + appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies(request) })); } /** @@ -146,8 +158,21 @@ export function assertSameOrigin(request, actor) { const origin = request.headers.origin; if (!origin) return; - const host = request.headers.host; - const allowed = new Set([env.web.publicUrl, `http://${host}`, `https://${host}`]); + + // The host the visitor used is what the browser puts in `Origin`; behind a + // proxy that is the forwarded one, not the socket's. + const hosts = [request.headers['x-forwarded-host'], request.headers.host] + .map((value) => + String(value ?? '') + .split(',')[0] + .trim(), + ) + .filter(Boolean); + const allowed = new Set([ + env.web.publicUrl, + ...hosts.flatMap((host) => [`http://${host}`, `https://${host}`]), + ]); + if (!allowed.has(origin.replace(/\/+$/, ''))) { throw forbidden('Requête rejetée : origine inattendue'); } diff --git a/src/web/public/views/login.js b/src/web/public/views/login.js index cdaa4e3..60711fd 100644 --- a/src/web/public/views/login.js +++ b/src/web/public/views/login.js @@ -6,10 +6,10 @@ import { button, field, input, notice, toast } from '../core/ui.js'; const ERRORS = { 'oauth-not-configured': - 'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET` et `WEB_PUBLIC_URL`, puis redémarre le bot.', + 'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET`, puis redémarre le bot.', 'state-mismatch': 'La session de connexion a expiré. Réessaie.', 'exchange-failed': - 'Discord a refusé l’échange du code. Vérifie l’URL de redirection déclarée dans le portail.', + 'Discord a refusé l’échange du code : la redirection déclarée dans le portail ne correspond pas à celle ci-dessous.', 'not-a-member': 'Ton compte Discord n’est pas membre du serveur FWS.', 'insufficient-level': 'Ton compte n’a pas le rôle Staff, Dev ou Owner sur le serveur.', 'missing-code': 'Discord n’a pas renvoyé de code d’autorisation.', @@ -54,6 +54,19 @@ export function render(host, { state }) { 'warning', ), + // The redirect is derived from the address in use, so it is the exact + // value to paste in the portal — port included. + config.redirectUri && + h( + 'details', + { class: 'muted', style: { textAlign: 'left', width: '100%' } }, + h('summary', { text: 'Redirection OAuth2 à déclarer dans le Developer Portal' }), + h('pre', {}, h('code', { text: config.redirectUri })), + h('p', { + text: 'Developer Portal → ton application → OAuth2 → Redirects. Elle doit être identique au caractère près, port compris.', + }), + ), + config.setupAvailable && h( 'div', diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js index 3c18578..81a78bb 100644 --- a/src/web/services/env-schema.js +++ b/src/web/services/env-schema.js @@ -98,7 +98,8 @@ export const SECTIONS = Object.freeze([ 'Le tableau de bord réutilise la connexion Discord des membres. Il faut donc déclarer une URL de redirection OAuth2 dans le Developer Portal.', steps: [ 'Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.', - 'Toujours dans **OAuth2 → Redirects**, ajoute exactement `{WEB_PUBLIC_URL}/auth/callback`.', + 'Toujours dans **OAuth2 → Redirects**, ajoute exactement l’URL affichée dans **Paramètres → Tableau de bord** : c’est l’adresse par laquelle tu ouvres le site, suivie de `/auth/callback`.', + 'Si le site répond sur un port différent de celui annoncé par ton hébergeur, c’est bien le port que tu utilises dans le navigateur qu’il faut déclarer.', 'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.', 'Laisse `WEB_HOST` sur `127.0.0.1` et place un reverse proxy HTTPS devant, sauf en développement local.', ], @@ -457,7 +458,7 @@ export const VARIABLES = Object.freeze([ key: 'WEB_PUBLIC_URL', section: 'web', label: 'URL publique', - help: 'URL par laquelle les membres accèdent au site. La redirection OAuth2 à déclarer est cette URL suivie de `/auth/callback`.', + help: 'URL de partage du site, utilisée dans les liens. La redirection OAuth2 est déduite de l’adresse réellement utilisée par le navigateur : ce champ n’est qu’un repli.', type: 'url', placeholder: 'https://bot.exemple.org', restartRequired: true, @@ -701,7 +702,7 @@ export function crossCheck(values) { if (read('WEB_ENABLED') === 'true') { if (!read('WEB_PUBLIC_URL')) { warnings.push( - 'Le tableau de bord est activé mais `WEB_PUBLIC_URL` est vide : la connexion Discord échouera.', + 'Le tableau de bord est activé sans `WEB_PUBLIC_URL` : la connexion Discord fonctionnera, mais les liens partagés vers le site seront incomplets.', ); } if (!read('DISCORD_CLIENT_SECRET')) { diff --git a/tests/web-auth.test.js b/tests/web-auth.test.js index 272e59e..17458b5 100644 --- a/tests/web-auth.test.js +++ b/tests/web-auth.test.js @@ -9,7 +9,7 @@ import { revokeApiToken, } from '../src/database/repositories/web-session-repository.js'; import { authorize } from '../src/web/auth/guard.js'; -import { resolveAccessLevel } from '../src/web/auth/discord-oauth.js'; +import { redirectUri, requestOrigin, resolveAccessLevel } from '../src/web/auth/discord-oauth.js'; import { assertSameOrigin, authenticate, @@ -227,3 +227,38 @@ describe('oauth access level', () => { assert.equal(resolveAccessLevel({ member: null, userId: '2', guildOwnerId: '1', roles }), null); }); }); + +describe('oauth redirect', () => { + it('follows the address the visitor actually used', () => { + // A hosting panel can publish the site on another port than the one + // announced by `WEB_PUBLIC_URL`; the browser's address is what Discord + // compares against. + const request = fakeRequest({ host: 'bot.example:25571' }); + assert.equal(requestOrigin(request), 'http://bot.example:25571'); + assert.equal(redirectUri(request), 'http://bot.example:25571/auth/callback'); + }); + + it('honours a reverse proxy', () => { + const request = fakeRequest({ + host: '127.0.0.1:3080', + 'x-forwarded-host': 'bot.example', + 'x-forwarded-proto': 'https', + }); + assert.equal(redirectUri(request), 'https://bot.example/auth/callback'); + }); + + it('keeps only the left-most forwarded value', () => { + const request = fakeRequest({ + host: 'interne:3080', + 'x-forwarded-host': 'bot.example, interne', + 'x-forwarded-proto': 'https, http', + }); + assert.equal(requestOrigin(request), 'https://bot.example'); + }); + + it('falls back to the configured URL when there is no request', () => { + // `WEB_PUBLIC_URL` is unset in the tests, so nothing can be built. + assert.equal(requestOrigin(undefined), ''); + assert.equal(redirectUri(undefined), ''); + }); +}); From a0428e05495df30198b95a17f467a97179743630 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:34:09 +0200 Subject: [PATCH 13/51] fix(web): keep the sidebar in step with the page being shown Navigating only swapped the main area, so the highlighted entry stayed on whichever page the shell was built with and nothing on screen said where you were. The highlight is now refreshed on every navigation, carries `aria-current` for screen readers and an inset marker that reads at a glance, and the browser tab takes the page name. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/app.js | 27 ++++++++++++++++++++++++--- src/web/public/styles.css | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/web/public/app.js b/src/web/public/app.js index 41b81bc..23a54c3 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -132,9 +132,26 @@ const currentRoute = () => { return { segments, path }; }; -function sidebar() { +/** + * Marks the current entry in the sidebar and retitles the tab. + * + * Navigation only swaps the main area, so the highlight has to be refreshed on + * its own — otherwise it keeps pointing at the page you arrived on. + */ +function highlightNav() { const { segments } = currentRoute(); const active = segments[0] ?? ''; + const route = ROUTES.find((entry) => entry.path === active); + + for (const link of document.querySelectorAll('.nav a')) { + link.classList.toggle('active', link.getAttribute('href') === `#/${active}`); + if (link.getAttribute('href') === `#/${active}`) link.setAttribute('aria-current', 'page'); + else link.removeAttribute('aria-current'); + } + document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; +} + +function sidebar() { const visible = ROUTES.filter( (route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'), ); @@ -163,7 +180,7 @@ function sidebar() { group.routes.map((route) => h( 'a', - { href: `#/${route.path}`, class: route.path === active ? 'active' : '' }, + { href: `#/${route.path}` }, h('span', { class: 'nav-icon', text: route.icon }), h('span', { text: route.label }), ), @@ -226,6 +243,8 @@ function applyModeButtons(node) { async function renderView(host) { const { segments } = currentRoute(); const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); + highlightNav(); + host.scrollIntoView?.({ block: 'start' }); if (!route) { mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' }))); @@ -285,7 +304,9 @@ async function boot() { state.config = config; window.addEventListener('hashchange', () => { - if (state.me?.authenticated && state.me.source !== 'setup') renderView(qs('.main')); + const main = qs('.main'); + // Without the shell in place there is nothing to swap, so rebuild the page. + if (main && state.me?.authenticated && state.me.source !== 'setup') renderView(main); else render(); }); window.addEventListener('unhandledrejection', (event) => { diff --git a/src/web/public/styles.css b/src/web/public/styles.css index f75ba4b..f24040a 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -192,6 +192,11 @@ pre code { background: color-mix(in srgb, var(--blue) 18%, transparent); color: var(--blue-soft); font-weight: 600; + /* Inset rather than a border: a real border would shift the label. */ + box-shadow: inset 3px 0 0 var(--blue); +} +.nav a.active .nav-icon { + opacity: 1; } .nav-icon { width: 1.15rem; @@ -685,6 +690,27 @@ pre code { padding-left: 1.2rem; } +details summary { + cursor: pointer; + font-size: 0.85rem; + font-weight: 600; + color: var(--text-muted); + padding: 0.35rem 0; + list-style-position: outside; +} +details summary:hover { + color: var(--text); +} +details[open] summary { + margin-bottom: 0.6rem; +} +details > *:not(summary) { + margin-bottom: 0.6rem; +} +details > *:last-child { + margin-bottom: 0; +} + /* --- Simple / advanced mode ---------------------------------------------- */ body[data-mode='simple'] .advanced-only { From ff15dfe92f75088ffe03b60ef0f0f42d0d24b73a Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:34:16 +0200 Subject: [PATCH 14/51] fix(web): let a deploy target be created without a reachable Gitea MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The « Nouvelle cible » button was hidden whenever the repository list came back empty, and a Gitea answering 403 took the whole page down with it — so a forge problem removed every way to set up a deployment, including webhook and shell targets that never talk to Gitea at all. The list is now a convenience: its failure is reported as a warning and the repository falls back to a free-text field. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/views/deployments.js | 36 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js index ca7421b..9425501 100644 --- a/src/web/public/views/deployments.js +++ b/src/web/public/views/deployments.js @@ -45,10 +45,17 @@ const KIND_HELP = { async function editTarget(existing, repositories, commandsAllowed, level, reload) { const name = input({ value: existing?.name ?? '', placeholder: 'production-web' }); - const repository = select( - repositories.map((item) => ({ value: item.fullName, label: item.fullName })), - { value: existing?.repository ?? repositories[0]?.fullName }, - ); + + // A webhook or a shell command needs no Gitea at all, so an unreachable forge + // must not stand between the user and a deploy target: the repository then + // falls back to a free-text field. + const repository = + repositories.length > 0 + ? select( + repositories.map((item) => ({ value: item.fullName, label: item.fullName })), + { value: existing?.repository ?? repositories[0]?.fullName }, + ) + : input({ value: existing?.repository ?? '', placeholder: 'FWS/FWS-Arch' }); const environment = input({ value: existing?.environment ?? 'production' }); const kindOptions = KINDS.filter( (kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER), @@ -104,7 +111,12 @@ async function editTarget(existing, repositories, commandsAllowed, level, reload 'div', { class: 'stack' }, field('Nom', name), - field('Dépôt', repository), + field('Dépôt', repository, { + help: + repositories.length > 0 + ? undefined + : 'Format `organisation/depot`. La liste est vide : Gitea est injoignable ou non configuré.', + }), field('Environnement', environment, { help: 'production, staging, preview…' }), field('Type', kind), help, @@ -116,7 +128,7 @@ async function editTarget(existing, repositories, commandsAllowed, level, reload ), toggle(enabled, (checked) => (enabled = checked), 'Cible active'), ), - submit: () => name.value.trim() !== '', + submit: () => name.value.trim() !== '' && repository.value.trim() !== '', }), { confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' }, ); @@ -211,15 +223,18 @@ export function render(host, { state }) { return renderAsync( host, async () => { + // The repository list is a convenience, not a prerequisite: a Gitea that + // answers 403 must not take the whole deployment page down with it. const [targets, deployments, repositories] = await Promise.all([ api.get('/api/deploy/targets'), api.get('/api/deployments', { limit: 40 }), - api.get('/api/repositories'), + api.get('/api/repositories').catch((error) => ({ repositories: [], error: error.message })), ]); return { ...targets, deployments: deployments.deployments, repositories: repositories.repositories ?? [], + repositoriesError: repositories.error ?? null, }; }, (data) => @@ -239,7 +254,6 @@ export function render(host, { state }) { }), ), level >= LEVELS.DEV && - data.repositories.length > 0 && button( 'Nouvelle cible', () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload), @@ -247,6 +261,12 @@ export function render(host, { state }) { ), ), + data.repositoriesError && + notice( + `Liste des dépôts indisponible (${data.repositoriesError}). Tu peux quand même créer une cible en saisissant le dépôt à la main ; seules les cibles Gitea Actions ont réellement besoin de la forge.`, + 'warning', + ), + !data.commandDeploysAllowed && notice( 'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.', From 9c6297e00e812ebd7850187e653c2f0b1fd3e9e9 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:34:16 +0200 Subject: [PATCH 15/51] fix(web): always offer the bootstrap token on the sign-in page The field only appeared when a token was already configured, which hid the one way back into the configuration exactly when Discord sign-in is broken or not set up yet. It is now always present, and says how to obtain a token when none is available. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/views/login.js | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/web/public/views/login.js b/src/web/public/views/login.js index 60711fd..bf7f899 100644 --- a/src/web/public/views/login.js +++ b/src/web/public/views/login.js @@ -67,16 +67,26 @@ export function render(host, { state }) { }), ), - config.setupAvailable && - h( - 'div', - { class: 'stack' }, - h('hr', { style: { border: 'none', borderTop: '1px solid var(--border)', width: '100%' } }), - field('Jeton d’amorçage', tokenInput, { - help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration.', - }), - button('Ouvrir l’assistant de configuration', submitSetupToken, { tone: 'ghost' }), - ), + // Always reachable: when Discord sign-in is broken or not set up yet, + // this is the only way back into the configuration, and hiding it left + // no visible way out. + h( + 'details', + { class: 'stack', style: { textAlign: 'left', width: '100%' }, open: !config.oauthConfigured }, + h('summary', { text: 'Se connecter avec un jeton de configuration' }), + field('Jeton d’amorçage', tokenInput, { + help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration, jamais au reste du site.', + }), + !config.setupAvailable && + notice( + 'Aucun jeton n’est configuré pour l’instant. Renseigne `WEB_SETUP_TOKEN` dans le .env puis redémarre le bot, ou lance `npm run setup` pour en obtenir un temporaire.', + 'info', + ), + button('Ouvrir l’assistant de configuration', submitSetupToken, { + tone: 'ghost', + disabled: !config.setupAvailable, + }), + ), ), ), ); From df89cc5893d581ff4f35b87e65f79cc6bc0c0357 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:39:59 +0200 Subject: [PATCH 16/51] feat(web): push live updates to the dashboard Reading a page and wondering whether it is still true is a poor way to watch a deployment, and polling every page on a timer costs far more than it returns. The server keeps one `text/event-stream` per open tab and publishes on it: a write once it has actually succeeded, tagged with the page it concerns, a deployment when it starts and when it ends, an incoming Gitea webhook, plus a tick and a heartbeat that stops proxies closing an idle stream. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/api/index.js | 11 ++ src/web/events.js | 135 +++++++++++++++++++++ src/web/server.js | 12 +- src/web/services/deploy-service.js | 4 + src/webhooks/gitea-webhook.js | 3 + tests/web-events.test.js | 187 +++++++++++++++++++++++++++++ 6 files changed, 351 insertions(+), 1 deletion(-) create mode 100644 src/web/events.js create mode 100644 tests/web-events.test.js diff --git a/src/web/api/index.js b/src/web/api/index.js index 7705500..f656efa 100644 --- a/src/web/api/index.js +++ b/src/web/api/index.js @@ -1,4 +1,6 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; import { registerAuthRoutes } from '../auth/routes.js'; +import { openEventStream } from '../events.js'; import { registerCommunityRoutes } from './community.js'; import { registerConfigurationRoutes } from './configuration.js'; import { registerDeploymentRoutes } from './deployments.js'; @@ -30,6 +32,15 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) { registerAuthRoutes(router); registerConfigurationRoutes(router); + // Long-lived stream the pages listen to instead of polling (M16-T12). + router.get( + '/api/events', + ({ request, response, actor }) => { + openEventStream(request, response, actor); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + // In bootstrap mode the bot is not connected and the database may be empty: // only the wizard makes sense. if (setupOnly) return router; diff --git a/src/web/events.js b/src/web/events.js new file mode 100644 index 0000000..1cf81af --- /dev/null +++ b/src/web/events.js @@ -0,0 +1,135 @@ +import { createLogger } from '../core/logger.js'; + +/** + * Server-sent events feeding the dashboard live (M16-T12). + * + * One long-lived GET per open tab, pushed to rather than polled: a browser that + * nobody is looking at costs a heartbeat every 25 seconds, and a change shows up + * as soon as it happens instead of on the next timer. + */ + +const log = createLogger('web:events'); + +const HEARTBEAT_MS = 25_000; +const TICK_MS = 15_000; +/** Past this, something is wrong: refuse rather than pile up dead sockets. */ +const MAX_SUBSCRIBERS = 64; + +const subscribers = new Set(); +let heartbeat = null; +let tick = null; + +function write(subscriber, payload) { + try { + subscriber.response.write(payload); + } catch (error) { + log.debug('Dropping a closed event subscriber', error); + remove(subscriber); + } +} + +function remove(subscriber) { + if (!subscribers.delete(subscriber)) return; + try { + subscriber.response.end(); + } catch { + // The socket is already gone, which is exactly why we are here. + } + if (subscribers.size === 0) stopTimers(); +} + +function startTimers() { + if (heartbeat) return; + // Comment frames keep proxies from closing an idle stream. + heartbeat = setInterval(() => { + for (const subscriber of subscribers) write(subscriber, ': ping\n\n'); + }, HEARTBEAT_MS); + tick = setInterval(() => broadcast('tick', { at: new Date().toISOString() }), TICK_MS); + + // Timers must never be the reason the process stays alive. + heartbeat.unref?.(); + tick.unref?.(); +} + +function stopTimers() { + clearInterval(heartbeat); + clearInterval(tick); + heartbeat = null; + tick = null; +} + +/** Publishes an event to every open dashboard. Never throws. */ +export function broadcast(topic, payload = {}) { + if (subscribers.size === 0) return 0; + + const frame = `event: ${topic}\ndata: ${JSON.stringify({ topic, ...payload })}\n\n`; + for (const subscriber of subscribers) write(subscriber, frame); + return subscribers.size; +} + +/** + * Registers a subscriber and keeps the response open. + * Returns nothing: the router must not try to serialise a body onto it. + */ +export function openEventStream(request, response, actor) { + if (subscribers.size >= MAX_SUBSCRIBERS) { + response.writeHead(503).end(); + return; + } + + response.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + // `no-transform` and the nginx hint both matter: a buffering proxy turns a + // live stream into a stream that arrives all at once, much later. + 'Cache-Control': 'no-cache, no-transform', + 'X-Accel-Buffering': 'no', + Connection: 'keep-alive', + 'X-Content-Type-Options': 'nosniff', + }); + response.flushHeaders?.(); + + const subscriber = { response, userId: actor?.userId ?? null }; + subscribers.add(subscriber); + startTimers(); + + write(subscriber, `retry: 5000\nevent: ready\ndata: ${JSON.stringify({ topic: 'ready' })}\n\n`); + + request.on('close', () => remove(subscriber)); + request.on('error', () => remove(subscriber)); + log.debug('Event subscriber connected', { subscribers: subscribers.size }); +} + +export function subscriberCount() { + return subscribers.size; +} + +/** Closes every stream, so a shutdown does not hang on open sockets. */ +export function closeEventStreams() { + for (const subscriber of [...subscribers]) remove(subscriber); + stopTimers(); +} + +/** + * Turns an API path into the topic a view can filter on, so a write made + * anywhere refreshes the pages that care and only those. + */ +export function topicForPath(pathname) { + const [, , section] = pathname.split('/'); + switch (section) { + case 'deploy': + case 'deployments': + return 'deployments'; + case 'repositories': + case 'organization': + return 'gitea'; + case 'discord': + return 'discord'; + case 'community': + return 'community'; + case 'settings': + case 'configuration': + return 'settings'; + default: + return 'mutation'; + } +} diff --git a/src/web/server.js b/src/web/server.js index e58550f..76fda41 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -8,6 +8,7 @@ import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js'; import { registerApiRoutes } from './api/index.js'; import { authenticate, assertSameOrigin } from './auth/session.js'; import { authorize } from './auth/guard.js'; +import { broadcast, closeEventStreams, topicForPath } from './events.js'; import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; import { createRouter } from './router.js'; @@ -102,8 +103,15 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da context, }); - // A handler that wrote the response itself (a redirect) returns nothing. + // A handler that wrote the response itself (a redirect, an event stream) + // returns nothing. if (!response.headersSent) sendJson(response, 200, result ?? { ok: true }); + + // Announce the change only once it has gone through, so a dashboard never + // refreshes on a write that was rejected. + if (request.method !== 'GET') { + broadcast(topicForPath(pathname), { path: pathname, method: request.method }); + } } catch (error) { const status = statusOf(error); if (status >= 500) log.error(`${request.method} ${pathname} failed`, error); @@ -127,6 +135,8 @@ export function startWebServer({ client = null, setupOnly = false } = {}) { log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly }); }); server.on('error', (error) => log.error('Dashboard server error', error)); + // Open event streams would otherwise keep the server from closing. + server.on('close', closeEventStreams); return server; } diff --git a/src/web/services/deploy-service.js b/src/web/services/deploy-service.js index 3fb62d9..b780fca 100644 --- a/src/web/services/deploy-service.js +++ b/src/web/services/deploy-service.js @@ -12,6 +12,7 @@ import { import { logEvent } from '../../database/repositories/event-log-repository.js'; import { notify } from '../../services/notifications/notification-service.js'; import { splitRepository, repos } from '../../services/gitea/gitea-admin.js'; +import { broadcast } from '../events.js'; import { HttpError, badRequest, forbidden } from '../http.js'; /** Runs a deployment for a target and records its outcome (M16-T07). */ @@ -156,6 +157,7 @@ export async function runDeployment( triggeredBy, }); markRunning(deployment.id); + broadcast('deployments', { id: deployment.id, status: 'running', target: target.name }); const payload = { deploymentId: deployment.id, @@ -177,12 +179,14 @@ export async function runDeployment( else output = await runGiteaAction(target, payload); finishDeployment(deployment.id, { status: 'success', log: output }); + broadcast('deployments', { id: deployment.id, status: 'success', target: target.name }); logEvent({ guildId, type: 'deploy.success', actorId: triggeredBy, payload }); await announce(client, { ...payload, status: 'success' }); return { ...deployment, status: 'success', log: output }; } catch (error) { const details = error.details ?? error.message; finishDeployment(deployment.id, { status: 'failed', log: details, error: error.message }); + broadcast('deployments', { id: deployment.id, status: 'failed', target: target.name }); log.error('Deployment failed', error); logEvent({ guildId, type: 'deploy.failed', actorId: triggeredBy, payload }); await announce(client, { ...payload, status: 'failed', error: error.message }); diff --git a/src/webhooks/gitea-webhook.js b/src/webhooks/gitea-webhook.js index 12dd1bc..70bae6e 100644 --- a/src/webhooks/gitea-webhook.js +++ b/src/webhooks/gitea-webhook.js @@ -5,6 +5,7 @@ import { getDatabase } from '../database/index.js'; import { logEvent } from '../database/repositories/event-log-repository.js'; import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js'; import { notify } from '../services/notifications/notification-service.js'; +import { broadcast } from '../web/events.js'; const log = createLogger('webhooks'); @@ -60,6 +61,8 @@ export async function handleGiteaWebhook(client, headers, rawBody) { payload: { deliveryId, type: notification.type }, }); + broadcast('gitea', { event, repository: payload.repository?.full_name ?? null }); + await notify(client, notification.type, { embeds: [notification.embed], content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined, diff --git a/tests/web-events.test.js b/tests/web-events.test.js new file mode 100644 index 0000000..cd6bf8c --- /dev/null +++ b/tests/web-events.test.js @@ -0,0 +1,187 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { createApiToken } from '../src/database/repositories/web-session-repository.js'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { hashToken } from '../src/web/auth/session.js'; +import { broadcast, closeEventStreams, subscriberCount, topicForPath } from '../src/web/events.js'; +import { createHandler } from '../src/web/server.js'; + +/** Live updates pushed over server-sent events (M16-T12). */ + +const TOKEN = 'fws_events-test-token'; + +/** Reads SSE frames off the socket until `stop()` is called. */ +function openStream(url) { + const controller = new AbortController(); + const frames = []; + let resolveReady; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + const done = fetch(url, { + headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'text/event-stream' }, + signal: controller.signal, + }).then(async (response) => { + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/event-stream/); + resolveReady(response); + + const decoder = new TextDecoder(); + try { + for await (const chunk of response.body) frames.push(decoder.decode(chunk, { stream: true })); + } catch { + // Aborting the request is how the test ends the stream. + } + }); + + return { ready, frames, stop: () => controller.abort(), done }; +} + +/** Events land asynchronously; give the socket a moment to deliver. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 120)); + +describe('event topics', () => { + it('routes a write to the pages that care about it', () => { + assert.equal(topicForPath('/api/deploy/targets/3/run'), 'deployments'); + assert.equal(topicForPath('/api/deployments'), 'deployments'); + assert.equal(topicForPath('/api/repositories/FWS/Arch/issues'), 'gitea'); + assert.equal(topicForPath('/api/organization'), 'gitea'); + assert.equal(topicForPath('/api/discord/announce'), 'discord'); + assert.equal(topicForPath('/api/community/tickets/1/close'), 'community'); + assert.equal(topicForPath('/api/settings/values/x'), 'settings'); + assert.equal(topicForPath('/api/auth/logout'), 'mutation'); + }); + + it('does nothing when nobody is listening', () => { + assert.equal(broadcast('tick', {}), 0); + }); +}); + +describe('event stream', () => { + let server; + let base; + + before(async () => { + initDatabase(':memory:'); + createApiToken({ + name: 'events', + tokenHash: hashToken(TOKEN), + prefix: TOKEN.slice(0, 12), + accessLevel: ACCESS_LEVELS.OWNER, + }); + + server = createServer(createHandler({ client: null, setupOnly: false })); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + base = `http://127.0.0.1:${server.address().port}`; + }); + + after(async () => { + closeEventStreams(); + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses an anonymous listener', async () => { + const response = await fetch(`${base}/api/events`); + assert.equal(response.status, 401); + }); + + it('greets a subscriber and counts it', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(subscriberCount(), 1); + assert.match(stream.frames.join(''), /event: ready/); + assert.match(stream.frames.join(''), /retry: 5000/); + + stream.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); + + it('pushes a broadcast to the open streams', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(broadcast('deployments', { id: 7, status: 'running' }), 1); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"id":7/); + assert.match(received, /"topic":"deployments"/); + + stream.stop(); + await settle(); + }); + + it('announces a successful write, and only once it succeeded', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + const write = (body) => + fetch(`${base}/api/deploy/targets`, { + method: 'POST', + headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + const rejected = await write({ name: '', repository: 'nope', kind: 'webhook' }); + assert.equal(rejected.status, 400); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + const accepted = await write({ + name: 'production', + repository: 'FWS/FWS-Arch', + kind: 'webhook', + config: { url: 'https://deploy.example/hook' }, + }); + assert.equal(accepted.status, 200); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"method":"POST"/); + + stream.stop(); + await settle(); + }); + + it('stays silent on a read', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + await fetch(`${base}/api/deployments`, { headers: { Authorization: `Bearer ${TOKEN}` } }); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + stream.stop(); + await settle(); + }); + + it('serves several dashboards at once', async () => { + const first = openStream(`${base}/api/events`); + const second = openStream(`${base}/api/events`); + await Promise.all([first.ready, second.ready]); + await settle(); + + assert.equal(broadcast('gitea', { event: 'push' }), 2); + await settle(); + + assert.match(first.frames.join(''), /event: gitea/); + assert.match(second.frames.join(''), /event: gitea/); + + first.stop(); + second.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); +}); From 5481e79dc40780799f11e644e184174ab51fbc80 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:39:59 +0200 Subject: [PATCH 17/51] feat(web): refresh the pages as the events arrive One `EventSource` for the whole dashboard, held in a single slot: a view that re-renders itself would otherwise register a second listener each time and double the work on every event. A refresh landing under someone's fingers is worse than data a few seconds old, so it waits while a dialog is open or a field has focus, a burst of writes collapses into one reload, and a background tab closes its stream. The Discord page stays off the tick because listing members calls the Discord API. When the stream cannot be established a timer takes over. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/app.js | 33 ++++++ src/web/public/core/live.js | 168 +++++++++++++++++++++++++++ src/web/public/styles.css | 36 ++++++ src/web/public/views/community.js | 3 + src/web/public/views/deployments.js | 4 + src/web/public/views/organization.js | 3 + src/web/public/views/overview.js | 5 + src/web/public/views/settings.js | 3 + 8 files changed, 255 insertions(+) create mode 100644 src/web/public/core/live.js diff --git a/src/web/public/app.js b/src/web/public/app.js index 23a54c3..ca2dc5b 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -1,5 +1,6 @@ import { api } from './core/api.js'; import { h, mount, qs } from './core/dom.js'; +import { onStatus, resetSubscriptions, startLive } from './core/live.js'; import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js'; /** Shell, navigation and hash routing of the dashboard (M16-T11). */ @@ -151,6 +152,34 @@ function highlightNav() { document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; } +const LIVE_LABELS = { + live: 'À jour en direct', + connecting: 'Connexion…', + reconnecting: 'Reconnexion…', + polling: 'Rafraîchissement périodique', + paused: 'En pause (onglet en arrière-plan)', + idle: 'Hors ligne', +}; + +let stopWatchingStatus = null; + +/** Small footer badge: says whether the page is following the bot live. */ +function liveIndicator() { + const dot = h('span', { class: 'live-dot' }); + const label = h('span', { text: LIVE_LABELS.idle }); + const node = h('div', { class: 'live', title: 'État de la mise à jour automatique' }, dot, label); + + stopWatchingStatus?.(); + stopWatchingStatus = onStatus(({ status, lastEventAt }) => { + node.dataset.status = status; + label.textContent = LIVE_LABELS[status] ?? status; + if (lastEventAt) { + node.title = `Dernière mise à jour à ${lastEventAt.toLocaleTimeString('fr-FR')}`; + } + }); + return node; +} + function sidebar() { const visible = ROUTES.filter( (route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'), @@ -196,6 +225,7 @@ function sidebar() { button('Simple', () => setMode('simple'), {}), button('Avancé', () => setMode('advanced'), {}), ), + liveIndicator(), h( 'div', { class: 'viewer' }, @@ -243,6 +273,7 @@ function applyModeButtons(node) { async function renderView(host) { const { segments } = currentRoute(); const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); + resetSubscriptions(); highlightNav(); host.scrollIntoView?.({ block: 'start' }); @@ -303,6 +334,8 @@ async function boot() { state.me = me; state.config = config; + startLive(); + window.addEventListener('hashchange', () => { const main = qs('.main'); // Without the shell in place there is nothing to swap, so rebuild the page. diff --git a/src/web/public/core/live.js b/src/web/public/core/live.js new file mode 100644 index 0000000..85e05d5 --- /dev/null +++ b/src/web/public/core/live.js @@ -0,0 +1,168 @@ +/** + * Live updates (M16-T12). + * + * One `EventSource` for the whole dashboard; views declare what they want to + * hear and get called back. When the stream cannot be established — a proxy + * that buffers, a network that drops it — a timer takes over so the pages still + * refresh, just less promptly. + */ + +/** + * A single slot rather than a list: exactly one view is on screen, and a view + * that re-renders itself on refresh would otherwise register a second listener + * each time, doubling the work on every event. + */ +let viewRefresher = null; +const STATUS_LISTENERS = new Set(); +const FALLBACK_MS = 30_000; +/** Backoff between reconnection attempts, capped so it always keeps trying. */ +const RETRY_MS = [2000, 5000, 15_000, 30_000]; + +let source = null; +let fallbackTimer = null; +let attempts = 0; +let status = 'idle'; +let lastEventAt = null; + +function setStatus(next) { + if (status === next) return; + status = next; + for (const listener of STATUS_LISTENERS) listener({ status, lastEventAt }); +} + +function emit(event) { + lastEventAt = new Date(); + try { + viewRefresher?.(event); + } catch { + // A failing view must not take the stream down with it. + } + setStatus(fallbackTimer ? 'polling' : 'live'); +} + +function startFallback() { + if (fallbackTimer) return; + fallbackTimer = setInterval(() => emit({ topic: 'tick', fallback: true }), FALLBACK_MS); + setStatus('polling'); +} + +function stopFallback() { + clearInterval(fallbackTimer); + fallbackTimer = null; +} + +function connect() { + if (source || document.hidden) return; + + setStatus(attempts === 0 ? 'connecting' : 'reconnecting'); + source = new EventSource('/api/events', { withCredentials: true }); + + source.addEventListener('open', () => { + attempts = 0; + stopFallback(); + setStatus('live'); + }); + + for (const topic of [ + 'ready', + 'tick', + 'mutation', + 'deployments', + 'gitea', + 'discord', + 'community', + 'settings', + ]) { + source.addEventListener(topic, (event) => { + let payload = { topic }; + try { + payload = { ...JSON.parse(event.data), topic }; + } catch { + // A frame we cannot read is still a signal that something moved. + } + emit(payload); + }); + } + + source.addEventListener('error', () => { + source?.close(); + source = null; + + // The browser reconnects on its own, but only while the page stays open and + // the server keeps answering; the timer covers the rest. + startFallback(); + const delay = RETRY_MS[Math.min(attempts, RETRY_MS.length - 1)]; + attempts += 1; + setTimeout(connect, delay); + }); +} + +/** Stops the stream while the tab is in the background, resumes on return. */ +document.addEventListener('visibilitychange', () => { + if (document.hidden) { + source?.close(); + source = null; + stopFallback(); + setStatus('paused'); + } else { + connect(); + // Coming back to the tab, the page is stale by definition. + emit({ topic: 'tick', resumed: true }); + } +}); + +export function startLive() { + connect(); +} + +export function onStatus(listener) { + STATUS_LISTENERS.add(listener); + listener({ status, lastEventAt }); + return () => STATUS_LISTENERS.delete(listener); +} + +export const liveStatus = () => ({ status, lastEventAt }); + +/** Drops the current view subscription, called when navigating elsewhere. */ +export function resetSubscriptions() { + viewRefresher = null; +} + +/** + * Re-runs `refresh` when a relevant event arrives. + * + * Refreshing under someone's fingers is worse than showing slightly old data, + * so a refresh is skipped while a dialog is open or a field has focus, and + * replayed once the way is clear. + */ +export function autoRefresh(refresh, { topics = ['tick'], minIntervalMs = 5000 } = {}) { + const wanted = new Set(topics); + let lastRun = Date.now(); + let pending = false; + + const busy = () => + document.querySelector('.overlay') !== null || + ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName); + + const run = () => { + if (busy()) { + pending = true; + return; + } + pending = false; + lastRun = Date.now(); + refresh(); + }; + + const listener = (event) => { + if (!wanted.has(event.topic) && !pending) return; + // A burst of writes must not turn into a burst of reloads. + if (Date.now() - lastRun < minIntervalMs && !pending) return; + run(); + }; + + viewRefresher = listener; + return () => { + if (viewRefresher === listener) viewRefresher = null; + }; +} diff --git a/src/web/public/styles.css b/src/web/public/styles.css index f24040a..94b8da0 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -690,6 +690,42 @@ pre code { padding-left: 1.2rem; } +.live { + display: flex; + align-items: center; + gap: 0.45rem; + font-size: 0.75rem; + color: var(--text-muted); + padding: 0 0.2rem; +} +.live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-muted); + flex: none; +} +.live[data-status='live'] .live-dot { + background: var(--green); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--green) 25%, transparent); +} +.live[data-status='polling'] .live-dot { + background: var(--amber); +} +.live[data-status='connecting'] .live-dot, +.live[data-status='reconnecting'] .live-dot { + background: var(--blue); + animation: pulse 1.2s ease-in-out infinite; +} +.live[data-status='paused'] .live-dot { + background: var(--border); +} +@keyframes pulse { + 50% { + opacity: 0.25; + } +} + details summary { cursor: pointer; font-size: 0.85rem; diff --git a/src/web/public/views/community.js b/src/web/public/views/community.js index 79cc128..f312536 100644 --- a/src/web/public/views/community.js +++ b/src/web/public/views/community.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatRelative, h } from '../core/dom.js'; import { badge, @@ -346,6 +347,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + autoRefresh(reload, { topics: ['community', 'discord', 'tick'] }); + return renderAsync( host, async () => { diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js index 9425501..1cf5502 100644 --- a/src/web/public/views/deployments.js +++ b/src/web/public/views/deployments.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatRelative, h, mount } from '../core/dom.js'; import { badge, @@ -220,6 +221,9 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + // A running deployment reports itself, so the log lands without a reload. + autoRefresh(reload, { topics: ['deployments', 'tick'], minIntervalMs: 2000 }); + return renderAsync( host, async () => { diff --git a/src/web/public/views/organization.js b/src/web/public/views/organization.js index 3ca94d0..c770d93 100644 --- a/src/web/public/views/organization.js +++ b/src/web/public/views/organization.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatBytes, formatRelative, h } from '../core/dom.js'; import { badge, @@ -104,6 +105,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const refresh = () => render(host, { state }); + autoRefresh(refresh, { topics: ['gitea'] }); + return renderAsync( host, () => api.get('/api/organization'), diff --git a/src/web/public/views/overview.js b/src/web/public/views/overview.js index 6ed05f7..7f46edb 100644 --- a/src/web/public/views/overview.js +++ b/src/web/public/views/overview.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js'; import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js'; @@ -162,6 +163,10 @@ function systemCard(database, features) { } export function render(host, { state }) { + autoRefresh(() => render(host, { state }), { + topics: ['tick', 'mutation', 'deployments', 'gitea', 'discord', 'community'], + }); + return renderAsync( host, () => api.get('/api/overview'), diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js index f565808..944126c 100644 --- a/src/web/public/views/settings.js +++ b/src/web/public/views/settings.js @@ -1,4 +1,5 @@ import { api } from '../core/api.js'; +import { autoRefresh } from '../core/live.js'; import { formatDate, formatRelative, h } from '../core/dom.js'; import { badge, @@ -436,6 +437,8 @@ export function render(host, { state }) { const level = state.me.accessLevel; const reload = () => render(host, { state }); + autoRefresh(reload, { topics: ['settings'] }); + return renderAsync( host, () => api.get('/api/settings'), From 2083133c7a3320e022388ede6ece038174ffdd84 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:39:59 +0200 Subject: [PATCH 18/51] docs(web): document the live updates Co-Authored-By: Claude Opus 5 (1M context) --- README.en.md | 2 ++ README.md | 2 ++ docs/web-dashboard.md | 31 +++++++++++++++++++++++++++---- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/README.en.md b/README.en.md index bb436fd..7e60bf3 100644 --- a/README.en.md +++ b/README.en.md @@ -340,6 +340,8 @@ The site reuses the access levels of the slash commands, derived from the Discor A **Simple / Advanced** switch hides or reveals the technical panels. It changes no permission: every call is checked again on the server. +The pages update on their own: the server pushes every change over a `text/event-stream`, and an indicator at the bottom of the sidebar says where the connection stands. Nothing reloads while a dialog is open or a field has focus, and a periodic refresh takes over when the stream cannot get through. + ### 6.3 Configuration wizard Every `.env` variable is described once, in `src/web/services/env-schema.js`: the form, the explanations, the validation and the generated file all derive from it. diff --git a/README.md b/README.md index 51c1654..bc9e7de 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,8 @@ Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Un commutateur **Simple / Avancé** masque ou révèle les panneaux techniques. Il ne change aucun droit : chaque appel est revérifié côté serveur. +Les pages se mettent à jour toutes seules : le serveur pousse chaque changement sur un flux `text/event-stream`, et un indicateur en bas de la barre latérale dit où en est la connexion. Rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus, et un rafraîchissement périodique prend le relais si le flux ne passe pas. + ### 6.3 Assistant de configuration Chaque variable du `.env` est décrite une seule fois, dans `src/web/services/env-schema.js` : le formulaire, les explications, la validation et le fichier généré en découlent tous. diff --git a/docs/web-dashboard.md b/docs/web-dashboard.md index f2e27de..ca7c161 100644 --- a/docs/web-dashboard.md +++ b/docs/web-dashboard.md @@ -119,7 +119,30 @@ Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en h Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec). -## 6. Jetons d'API +## 6. Mise à jour automatique + +Les pages suivent le bot en direct : aucun rafraîchissement manuel n'est nécessaire. + +Le serveur tient un flux `text/event-stream` sur `GET /api/events`, un par onglet ouvert. Il y publie : + +- **chaque écriture réussie** de l'API, étiquetée selon la page concernée (`deployments`, `gitea`, `discord`, `community`, `settings`) — une écriture rejetée ne déclenche rien ; +- **l'avancement des déploiements**, au démarrage puis à l'arrivée du résultat ; +- **les webhooks Gitea** reçus, dès qu'ils sont validés ; +- un **tick** toutes les 15 secondes, et un battement de cœur toutes les 25 secondes qui empêche les proxys de fermer un flux inactif. + +Côté navigateur, un seul `EventSource` sert tout le tableau de bord, et chaque page ne réagit qu'aux sujets qui la concernent. L'indicateur en bas de la barre latérale dit où en est la connexion. + +Trois garde-fous, parce qu'un rafraîchissement qui tombe au mauvais moment est pire qu'une donnée un peu vieille : + +- rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus — le rafraîchissement est rejoué ensuite ; +- une rafale d'écritures ne produit qu'un seul rechargement ; +- l'onglet en arrière-plan ferme son flux et le rouvre au retour. + +Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — un rafraîchissement périodique prend le relais automatiquement, et l'indicateur passe en orange. La page Serveur Discord est volontairement hors du tick : lister les membres appelle l'API Discord, elle ne se rafraîchit que sur un vrai changement. + +Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte. + +## 7. Jetons d'API Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée. @@ -129,7 +152,7 @@ curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment. -## 7. Sécurité +## 8. Sécurité - **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site. - **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`. @@ -140,7 +163,7 @@ Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personn - **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact. - **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur. -## 8. Fonctionnement interne +## 9. Fonctionnement interne ```text src/web/ @@ -184,7 +207,7 @@ Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le co Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port. -## 9. Dépannage +## 10. Dépannage | Symptôme | Cause probable | | ---------------------------------------------- | ------------------------------------------------------------------------------- | From a44ff0cb522c7df9ad1f924784a9831d1be211cf Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:47:46 +0200 Subject: [PATCH 19/51] fix(web): pin the sidebar highlight to the route, and name the build The highlight compared hrefs, which a trailing slash or a query string in the hash was enough to defeat, and it only ran once the view had loaded. Each link now carries the route it stands for and the highlight is applied as soon as the sidebar exists. The footer also states the running version and the date of the newest interface file. Deployments that ship an archive make it easy to look at a stale copy and wonder why a fix is missing; the page can now say so. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/api/index.js | 41 +++++++++++++++++++++++++++++++++++++++ src/web/public/app.js | 29 ++++++++++++++++++++++----- src/web/public/styles.css | 6 ++++++ 3 files changed, 71 insertions(+), 5 deletions(-) diff --git a/src/web/api/index.js b/src/web/api/index.js index f656efa..2f50d88 100644 --- a/src/web/api/index.js +++ b/src/web/api/index.js @@ -1,3 +1,6 @@ +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { ACCESS_LEVELS } from '../../config/constants.js'; import { registerAuthRoutes } from '../auth/routes.js'; import { openEventStream } from '../events.js'; @@ -12,6 +15,42 @@ import { registerReleaseRoutes } from './releases.js'; import { registerRepositoryRoutes } from './repositories.js'; import { registerSettingsRoutes } from './settings.js'; +const here = path.dirname(fileURLToPath(import.meta.url)); + +const VERSION = (() => { + try { + return JSON.parse(readFileSync(path.join(here, '../../../package.json'), 'utf8')).version; + } catch { + return 'inconnue'; + } +})(); + +/** + * Newest file of the served interface. + * + * Deployments that ship an archive make it easy to look at a stale copy and + * wonder why a fix is missing; this gives the page something to state. + */ +const BUILD_AT = (() => { + const root = path.join(here, '../public'); + let newest = 0; + + const walk = (directory) => { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) walk(target); + else newest = Math.max(newest, statSync(target).mtimeMs); + } + }; + + try { + walk(root); + } catch { + return null; + } + return newest > 0 ? new Date(newest).toISOString() : null; +})(); + /** * Route registration order matters only for readability: the router matches on * the full pattern, not on declaration order. @@ -25,6 +64,8 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) { status: context.client?.isReady?.() ? 'ok' : 'starting', setupOnly: context.setupOnly, uptimeMs: Date.now() - context.startedAt, + version: VERSION, + buildAt: BUILD_AT, }), { public: true }, ); diff --git a/src/web/public/app.js b/src/web/public/app.js index ca2dc5b..b4f7de5 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -139,14 +139,17 @@ const currentRoute = () => { * Navigation only swaps the main area, so the highlight has to be refreshed on * its own — otherwise it keeps pointing at the page you arrived on. */ -function highlightNav() { +function highlightNav(scope = document) { const { segments } = currentRoute(); const active = segments[0] ?? ''; const route = ROUTES.find((entry) => entry.path === active); - for (const link of document.querySelectorAll('.nav a')) { - link.classList.toggle('active', link.getAttribute('href') === `#/${active}`); - if (link.getAttribute('href') === `#/${active}`) link.setAttribute('aria-current', 'page'); + for (const link of scope.querySelectorAll('.nav a')) { + // Compare the route the link carries, not its href: a trailing slash or a + // query string in the hash must not make an entry look inactive. + const current = link.dataset.route === active; + link.classList.toggle('active', current); + if (current) link.setAttribute('aria-current', 'page'); else link.removeAttribute('aria-current'); } document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; @@ -209,7 +212,7 @@ function sidebar() { group.routes.map((route) => h( 'a', - { href: `#/${route.path}` }, + { href: `#/${route.path}`, dataset: { route: route.path } }, h('span', { class: 'nav-icon', text: route.icon }), h('span', { text: route.label }), ), @@ -226,6 +229,7 @@ function sidebar() { button('Avancé', () => setMode('advanced'), {}), ), liveIndicator(), + h('div', { class: 'build muted', text: '…' }), h( 'div', { class: 'viewer' }, @@ -320,9 +324,23 @@ export function render() { const shell = h('div', { class: 'shell' }, sidebar(), main); mount(app, shell); applyModeButtons(shell); + highlightNav(shell); renderView(main); } +/** Names the interface actually being served, archive deployments being easy to get wrong. */ +async function showBuild() { + const health = await api.get('/api/health').catch(() => null); + const node = qs('.build'); + if (!node || !health) return; + + const built = health.buildAt + ? new Date(health.buildAt).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' }) + : 'date inconnue'; + node.textContent = `v${health.version} · interface du ${built}`; + node.title = "Date du fichier d'interface le plus récent servi par le bot."; +} + async function boot() { document.body.dataset.mode = state.mode; document.documentElement.dataset.theme = state.theme; @@ -335,6 +353,7 @@ async function boot() { state.config = config; startLive(); + showBuild(); window.addEventListener('hashchange', () => { const main = qs('.main'); diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 94b8da0..3fd602c 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -690,6 +690,12 @@ pre code { padding-left: 1.2rem; } +.build { + font-size: 0.7rem; + padding: 0 0.2rem; + opacity: 0.75; +} + .live { display: flex; align-items: center; From d439b1b3e81cee032dde5e25e2bd9b6fecba624d Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 20:47:47 +0200 Subject: [PATCH 20/51] feat(web): make deploying reachable from where it is looked for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The « Déployer » button only existed on the row of an already created target, so an empty list was a dead end whose only way out sat in the page header. The empty state now carries the action that fills it. A release also gains its own deploy button: wanting to ship a given version is the moment people look for it, and sending them to another page to retype the tag was needless. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/core/ui.js | 8 +++- src/web/public/views/deployments.js | 19 +++++++- src/web/public/views/releases.js | 70 +++++++++++++++++++++++++++-- 3 files changed, 91 insertions(+), 6 deletions(-) diff --git a/src/web/public/core/ui.js b/src/web/public/core/ui.js index b3fec71..20121e7 100644 --- a/src/web/public/core/ui.js +++ b/src/web/public/core/ui.js @@ -81,7 +81,13 @@ export function toggle(checked, onChange, label) { * `render` returns a Node or a string. */ export function table(columns, rows, { empty = 'Rien à afficher pour le moment.' } = {}) { - if (!rows || rows.length === 0) return h('p', { class: 'empty', text: empty }); + if (!rows || rows.length === 0) { + // An empty state is where people look for the action that fills it, so it + // accepts a node and not only a sentence. + return empty instanceof Node + ? h('div', { class: 'empty' }, empty) + : h('p', { class: 'empty', text: empty }); + } return h( 'div', diff --git a/src/web/public/views/deployments.js b/src/web/public/views/deployments.js index 1cf5502..785a809 100644 --- a/src/web/public/views/deployments.js +++ b/src/web/public/views/deployments.js @@ -342,7 +342,24 @@ export function render(host, { state }) { }, ], data.targets, - { empty: 'Aucune cible pour l’instant. Crée-en une pour déployer depuis ce site.' }, + { + // The action that fills the table belongs in the table, not only + // in the page header where nobody looks for it. + empty: h( + 'div', + { class: 'stack', style: { alignItems: 'center' } }, + h('p', { + text: 'Aucune cible pour l’instant. Une cible dit où livrer un dépôt ; le bouton « Déployer » apparaît ensuite sur sa ligne.', + }), + level >= LEVELS.DEV + ? button( + 'Créer une première cible', + () => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload), + { tone: 'primary' }, + ) + : h('p', { class: 'muted', text: 'Le niveau Dev est requis pour en créer une.' }), + ), + }, ), ), diff --git a/src/web/public/views/releases.js b/src/web/public/views/releases.js index 0a56946..3a25b89 100644 --- a/src/web/public/views/releases.js +++ b/src/web/public/views/releases.js @@ -94,7 +94,51 @@ async function publishRelease(base, repository, releases, branches, reload) { reload(); } -function releaseRow(base, level, reload) { +/** Runs one of the repository's targets on a given version. */ +async function deployRelease(release, targets, reload) { + const runnable = targets.filter((target) => target.enabled); + if (runnable.length === 0) { + toast('Aucune cible active pour ce dépôt. Crée-en une depuis la page Déploiements.', 'error'); + return; + } + + const picker = select( + runnable.map((target) => ({ + value: String(target.id), + label: `${target.name} — ${target.environment}`, + })), + { value: String(runnable[0].id) }, + ); + const summary = h('p', { class: 'muted', text: runnable[0].summary }); + picker.addEventListener('change', () => { + summary.textContent = runnable.find((target) => String(target.id) === picker.value)?.summary ?? ''; + }); + + const confirmed = await modal( + `Déployer ${release.tag}`, + () => ({ + node: h('div', { class: 'stack' }, field('Cible', picker), summary), + submit: () => true, + }), + { confirmLabel: 'Déployer', tone: 'primary' }, + ); + if (!confirmed) return; + + toast('Déploiement lancé…', 'info'); + const result = await api.post(`/api/deploy/targets/${picker.value}/run`, { + releaseTag: release.tag, + ref: release.target || undefined, + }); + toast( + result.status === 'success' + ? `${release.tag} déployé.` + : `Déploiement en échec : ${result.error ?? 'raison inconnue'}`, + result.status === 'success' ? 'success' : 'error', + ); + reload(); +} + +function releaseRow(base, level, reload, targets) { return [ { label: 'Version', @@ -129,6 +173,9 @@ function releaseRow(base, level, reload) { 'div', { class: 'row' }, button('Notes', () => showNotes(release), { tone: 'ghost' }), + level >= LEVELS.DEV && + !release.draft && + button('Déployer', () => deployRelease(release, targets, reload), { tone: 'primary' }), level >= LEVELS.DEV && release.draft && button( @@ -197,12 +244,18 @@ export async function render(host, { state }) { renderAsync( body, async () => { - const [detail, releases, deployments] = await Promise.all([ + const [detail, releases, deployments, targets] = await Promise.all([ api.get(base), api.get(`${base}/releases`, { limit: 30 }), api.get('/api/deployments', { repository: current.fullName, limit: 15 }), + api.get('/api/deploy/targets', { repository: current.fullName }).catch(() => ({ targets: [] })), ]); - return { detail, releases: releases.releases, deployments: deployments.deployments }; + return { + detail, + releases: releases.releases, + deployments: deployments.deployments, + targets: targets.targets ?? [], + }; }, (data) => h( @@ -220,9 +273,18 @@ export async function render(host, { state }) { { tone: 'primary' }, ), }, - table(releaseRow(base, level, draw), data.releases, { empty: 'Aucune release publiée.' }), + table(releaseRow(base, level, draw, data.targets), data.releases, { + empty: 'Aucune release publiée.', + }), ), + level >= LEVELS.DEV && + data.targets.length === 0 && + notice( + 'Aucune cible de déploiement pour ce dépôt : le bouton « Déployer » apparaîtra une fois une cible créée depuis la page Déploiements.', + 'info', + ), + card( 'Déploiements liés', { subtitle: 'Déclenchés par la publication d’une version ou lancés à la main.' }, From 406b5af3ea9e9c03a2606e2641475996a477bbbc Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:23 +0200 Subject: [PATCH 21/51] feat(settings): make the server settings real, and widen them The dashboard offered seven switches that nothing read: they promised a behaviour the bot did not have, which is worse than offering nothing. Every setting is now declared once, with its type, its bounds and its explanation, and the services read it: the welcome message and its wording, the automatic role, departure notices, the private notice sent to a sanctioned member, the default mute duration, how much history a ban erases, whether a closed ticket is deleted or archived, and an optional role mention on the Gitea notifications. A test walks the sources and fails when a declared key is read nowhere, so the list cannot drift back into decoration. Co-Authored-By: Claude Opus 5 (1M context) --- src/commands/moderation/ban.js | 15 +- src/commands/moderation/kick.js | 9 +- src/commands/moderation/mute.js | 15 +- src/commands/moderation/warn.js | 19 +- src/config/guild-settings.js | 250 ++++++++++++++++++ src/events/guild-member-add.js | 3 +- src/services/members/member-service.js | 17 +- src/services/moderation/moderation-service.js | 14 + .../notifications/notification-service.js | 11 +- src/services/tickets/ticket-service.js | 16 +- src/web/api/settings.js | 96 ++----- src/web/public/views/settings.js | 114 +++++--- tests/guild-settings.test.js | 143 ++++++++++ 13 files changed, 576 insertions(+), 146 deletions(-) create mode 100644 src/config/guild-settings.js create mode 100644 tests/guild-settings.test.js diff --git a/src/commands/moderation/ban.js b/src/commands/moderation/ban.js index 61cfa6f..0a5f92f 100644 --- a/src/commands/moderation/ban.js +++ b/src/commands/moderation/ban.js @@ -1,8 +1,10 @@ import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ACCESS_LEVELS } from '../../config/constants.js'; +import { readSetting } from '../../config/guild-settings.js'; import { assertModerationTarget, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -27,16 +29,17 @@ export const data = new SlashCommandBuilder() export async function execute(interaction) { const user = interaction.options.getUser('user', true); const reason = interaction.options.getString('reason'); - const deleteDays = interaction.options.getInteger('delete_days') ?? 0; + // Falls back to what the server configured rather than to a blunt zero. + const deleteDays = + interaction.options.getInteger('delete_days') ?? + Math.round(readSetting('moderation.banDeleteMessageHours', interaction.guildId) / 24); const member = await interaction.guild.members.fetch(user.id).catch(() => null); if (member) { assertModerationTarget(interaction, member); - await member - .send({ - embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); + await notifyTarget(member, { + embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], + }); } await interaction.deferReply({ flags: MessageFlags.Ephemeral }); diff --git a/src/commands/moderation/kick.js b/src/commands/moderation/kick.js index c42da02..e073eba 100644 --- a/src/commands/moderation/kick.js +++ b/src/commands/moderation/kick.js @@ -4,6 +4,7 @@ import { assertModerationTarget, fetchTargetMember, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -26,11 +27,9 @@ export async function execute(interaction) { assertModerationTarget(interaction, target); await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], + }); await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`); await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); diff --git a/src/commands/moderation/mute.js b/src/commands/moderation/mute.js index bb9b120..bbb6039 100644 --- a/src/commands/moderation/mute.js +++ b/src/commands/moderation/mute.js @@ -1,10 +1,12 @@ import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ACCESS_LEVELS } from '../../config/constants.js'; +import { readSetting } from '../../config/guild-settings.js'; import { assertModerationTarget, fetchTargetMember, formatDuration, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -20,7 +22,6 @@ export const data = new SlashCommandBuilder() option .setName('minutes') .setDescription('Durée de la sanction, en minutes') - .setRequired(true) .setMinValue(1) .setMaxValue(40_320), ) @@ -29,7 +30,9 @@ export const data = new SlashCommandBuilder() /** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */ export async function execute(interaction) { const user = interaction.options.getUser('user', true); - const minutes = interaction.options.getInteger('minutes', true); + const minutes = + interaction.options.getInteger('minutes') ?? + readSetting('moderation.defaultMuteMinutes', interaction.guildId); const reason = interaction.options.getString('reason'); const durationMs = minutes * 60_000; @@ -45,11 +48,9 @@ export async function execute(interaction) { reason, durationMs, }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], + }); await interaction.editReply({ embeds: [ diff --git a/src/commands/moderation/warn.js b/src/commands/moderation/warn.js index 0c79d3f..f4ab60f 100644 --- a/src/commands/moderation/warn.js +++ b/src/commands/moderation/warn.js @@ -5,6 +5,7 @@ import { assertModerationTarget, fetchTargetMember, logModerationAction, + notifyTarget, targetNoticeEmbed, } from '../../services/moderation/moderation-service.js'; import { successEmbed } from '../../ui/embeds.js'; @@ -32,16 +33,14 @@ export async function execute(interaction) { await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason }); const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' }); - await target - .send({ - embeds: [ - targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ - name: 'Avertissements', - value: String(total), - }), - ], - }) - .catch(() => {}); + await notifyTarget(target, { + embeds: [ + targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ + name: 'Avertissements', + value: String(total), + }), + ], + }); await interaction.editReply({ embeds: [ diff --git a/src/config/guild-settings.js b/src/config/guild-settings.js new file mode 100644 index 0000000..99c48cd --- /dev/null +++ b/src/config/guild-settings.js @@ -0,0 +1,250 @@ +import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js'; +import { env } from './env.js'; + +/** + * Settings a server can change without touching the `.env` (M16-T13). + * + * Single source of truth: the form, the validation and the values the services + * read all come from here. A setting that is not read by anything has no + * business being in this list — a switch that does nothing is worse than no + * switch at all. + */ + +export const SETTING_SECTIONS = Object.freeze([ + { + id: 'welcome', + title: 'Arrivées et départs', + summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.', + }, + { id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' }, + { id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' }, + { + id: 'voice', + title: 'Salons vocaux', + summary: 'Salons temporaires créés par les déclencheurs.', + }, + { id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' }, + { id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' }, +]); + +export const GUILD_SETTINGS = Object.freeze([ + // --- Arrivées et départs --------------------------------------------------- + { + key: 'welcome.enabled', + section: 'welcome', + label: 'Message de bienvenue', + help: 'Publier un message dans le salon d’accueil à chaque arrivée.', + type: 'bool', + default: true, + }, + { + key: 'welcome.message', + section: 'welcome', + label: 'Texte de bienvenue', + help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.', + type: 'text', + default: 'Bienvenue sur le serveur **{server}** !', + maxLength: 500, + }, + { + key: 'welcome.showRules', + section: 'welcome', + label: 'Rappeler le règlement', + help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.', + type: 'bool', + default: true, + }, + { + key: 'welcome.directMessage', + section: 'welcome', + label: 'Message privé de bienvenue', + help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.', + type: 'bool', + default: false, + }, + { + key: 'members.autoRole', + section: 'welcome', + label: 'Attribuer le rôle d’arrivée', + help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.', + type: 'bool', + default: true, + }, + { + key: 'departure.announce', + section: 'welcome', + label: 'Annoncer les départs', + help: 'Publie une ligne dans les logs quand un membre quitte le serveur.', + type: 'bool', + default: true, + }, + + // --- Modération ------------------------------------------------------------ + { + key: 'moderation.dmTarget', + section: 'moderation', + label: 'Prévenir le membre sanctionné', + help: 'Envoie un message privé expliquant la sanction et son motif.', + type: 'bool', + default: true, + }, + { + key: 'moderation.defaultMuteMinutes', + section: 'moderation', + label: 'Durée d’exclusion par défaut (min)', + help: 'Proposée quand `/mute` est lancé sans durée.', + type: 'int', + default: 60, + min: 1, + max: 40_320, + }, + { + key: 'moderation.banDeleteMessageHours', + section: 'moderation', + label: 'Messages supprimés au bannissement (h)', + help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.', + type: 'int', + default: 0, + min: 0, + max: 168, + advanced: true, + }, + + // --- Tickets --------------------------------------------------------------- + { + key: 'tickets.deleteChannelOnClose', + section: 'tickets', + label: 'Supprimer le salon à la clôture', + help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.', + type: 'bool', + default: true, + }, + + // --- Salons vocaux --------------------------------------------------------- + { + key: 'voice.adoptOrphans', + section: 'voice', + label: 'Récupérer les salons orphelins', + help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.', + type: 'bool', + default: true, + }, + + // --- Notifications --------------------------------------------------------- + { + key: 'notifications.mentionRoleId', + section: 'notifications', + label: 'Rôle à mentionner', + help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.', + type: 'snowflake', + default: '', + advanced: true, + }, + + // --- Tableau de bord ------------------------------------------------------- + { + key: 'deploy.requireConfirmation', + section: 'interface', + label: 'Confirmation avant déploiement', + help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.', + type: 'bool', + default: true, + }, + { + key: 'web.defaultMode', + section: 'interface', + label: 'Mode d’affichage par défaut', + help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.', + type: 'enum', + options: ['simple', 'advanced'], + default: 'simple', + }, +]); + +export const SETTING_BY_KEY = Object.freeze( + Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])), +); + +/** Coerces a stored value to the declared type, falling back on the default. */ +function coerce(setting, value) { + if (value === null || value === undefined) return setting.default; + + switch (setting.type) { + case 'bool': + return Boolean(value); + case 'int': { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed)) return setting.default; + if (setting.min !== undefined && parsed < setting.min) return setting.min; + if (setting.max !== undefined && parsed > setting.max) return setting.max; + return parsed; + } + case 'enum': + return setting.options.includes(value) ? value : setting.default; + default: + return String(value); + } +} + +/** + * Reads a setting. Never throws: called from event handlers that must keep + * working even when the database is momentarily unavailable. + */ +export function readSetting(key, guildId = env.discord.guildId) { + const setting = SETTING_BY_KEY[key]; + if (!setting) throw new Error(`Unknown guild setting: ${key}`); + return coerce(setting, resolveSetting(guildId, key, setting.default)); +} + +/** Validates then stores a setting. Returns the stored value. */ +export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) { + const setting = SETTING_BY_KEY[key]; + if (!setting) throw new Error(`Unknown guild setting: ${key}`); + + const message = validateSetting(key, value); + if (message) throw new Error(message); + + const stored = coerce(setting, value); + setSetting(guildId, key, stored, updatedBy); + return stored; +} + +/** Returns null when the value is acceptable, a French message otherwise. */ +export function validateSetting(key, value) { + const setting = SETTING_BY_KEY[key]; + if (!setting) return `Réglage inconnu : ${key}`; + + switch (setting.type) { + case 'bool': + return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.'; + case 'int': { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.'; + if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`; + if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`; + return null; + } + case 'enum': + return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`; + case 'snowflake': { + const text = String(value ?? '').trim(); + return text === '' || /^\d{17,20}$/.test(text) + ? null + : 'Un identifiant Discord est composé de 17 à 20 chiffres.'; + } + default: { + const text = String(value ?? ''); + if (setting.maxLength && text.length > setting.maxLength) { + return `${setting.maxLength} caractères maximum.`; + } + return null; + } + } +} + +/** Every setting with its current value, for the settings page. */ +export function allSettings(guildId = env.discord.guildId) { + return Object.fromEntries( + GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]), + ); +} diff --git a/src/events/guild-member-add.js b/src/events/guild-member-add.js index 8b0b8e2..067ba92 100644 --- a/src/events/guild-member-add.js +++ b/src/events/guild-member-add.js @@ -1,4 +1,5 @@ import { Events } from 'discord.js'; +import { readSetting } from '../config/guild-settings.js'; import { createLogger } from '../core/logger.js'; import { assignMemberRole, @@ -16,5 +17,5 @@ export async function execute(client, member) { await assignMemberRole(member); await sendWelcome(client, member); - await sendWelcomeDirectMessage(member); + if (readSetting('welcome.directMessage', member.guild.id)) await sendWelcomeDirectMessage(member); } diff --git a/src/services/members/member-service.js b/src/services/members/member-service.js index 6f20982..0f907fc 100644 --- a/src/services/members/member-service.js +++ b/src/services/members/member-service.js @@ -1,5 +1,6 @@ import { COLORS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { createLogger } from '../../core/logger.js'; import { logEvent } from '../../database/repositories/event-log-repository.js'; import { baseEmbed } from '../../ui/embeds.js'; @@ -14,6 +15,10 @@ async function sendTo(channel) { /** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */ export async function sendWelcome(client, member) { + if (!readSetting('welcome.enabled', member.guild.id)) { + log.debug('Welcome message disabled for this guild'); + return; + } if (!env.channels.welcome) { log.debug('No welcome channel configured'); return; @@ -25,13 +30,17 @@ export async function sendWelcome(client, member) { return; } + const greeting = + readSetting('welcome.message', member.guild.id).replaceAll('{server}', member.guild.name) || + DEFAULT_WELCOME; + const embed = baseEmbed(COLORS.primary) .setTitle('🎉 Nouveau membre') - .setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`) + .setDescription(`${member} vient d’arriver. ${greeting}`) .addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true }) .setThumbnail(member.user.displayAvatarURL({ size: 128 })); - if (env.channels.rules) { + if (env.channels.rules && readSetting('welcome.showRules', member.guild.id)) { embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` }); } @@ -41,6 +50,8 @@ export async function sendWelcome(client, member) { /** Gives the default member role (M7-T03). */ export async function assignMemberRole(member) { + if (!readSetting('members.autoRole', member.guild.id)) return; + const roleId = env.roles.member; if (!roleId || member.roles.cache.has(roleId)) return; @@ -82,6 +93,8 @@ export async function sendWelcomeDirectMessage(member) { /** Logs a departure in the log channel (M7-T04). */ export async function announceDeparture(client, member) { + if (!readSetting('departure.announce', member.guild.id)) return; + const channelId = env.channels.logs || env.channels.modLogs; if (!channelId) return; diff --git a/src/services/moderation/moderation-service.js b/src/services/moderation/moderation-service.js index b0562f8..2afeae0 100644 --- a/src/services/moderation/moderation-service.js +++ b/src/services/moderation/moderation-service.js @@ -1,5 +1,6 @@ import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { UserFacingError } from '../../core/errors.js'; import { canActOn } from '../../core/permissions.js'; import { logEvent } from '../../database/repositories/event-log-repository.js'; @@ -95,6 +96,19 @@ export async function sendModerationLog( await channel.send({ embeds: [embed] }).catch(() => {}); } +/** + * Sends the private notice to the sanctioned member, when the server wants one + * (M8-T07). Never throws: plenty of accounts refuse direct messages, and that + * must not turn a successful sanction into an error. + */ +export async function notifyTarget(member, payload) { + if (!readSetting('moderation.dmTarget', member.guild.id)) return false; + return member + .send(payload) + .then(() => true) + .catch(() => false); +} + /** Direct message sent to the member who is being moderated (M8-T07). */ export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { const meta = MODERATION_ACTIONS[action]; diff --git a/src/services/notifications/notification-service.js b/src/services/notifications/notification-service.js index 1e0f5c9..8d9a6fd 100644 --- a/src/services/notifications/notification-service.js +++ b/src/services/notifications/notification-service.js @@ -1,4 +1,5 @@ import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { createLogger } from '../../core/logger.js'; import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; import { errorEmbed } from '../../ui/embeds.js'; @@ -58,7 +59,15 @@ export async function notify(client, type, payload) { log.warn(`Notification channel unavailable for ${type}`, { channelId }); return null; } - return channel.send(payload); + + // An optional ping, prepended rather than replacing whatever content the + // caller already prepared. + const mention = readSetting('notifications.mentionRoleId'); + const message = mention + ? { ...payload, content: payload.content ? `<@&${mention}> ${payload.content}` : `<@&${mention}>` } + : payload; + + return channel.send(message); } /** Reports an unexpected failure in the technical channel (M9-T07). */ diff --git a/src/services/tickets/ticket-service.js b/src/services/tickets/ticket-service.js index 4666d8c..ecd2890 100644 --- a/src/services/tickets/ticket-service.js +++ b/src/services/tickets/ticket-service.js @@ -1,5 +1,6 @@ import { ChannelType, PermissionFlagsBits } from 'discord.js'; import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; +import { readSetting } from '../../config/guild-settings.js'; import { env } from '../../config/env.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.js'; @@ -235,10 +236,13 @@ export async function closeTicket(interaction, reason = null) { payload: { ticketId: ticket.id, reason }, }); + const deleteChannel = readSetting('tickets.deleteChannelOnClose', ticket.guild_id); await interaction.reply({ embeds: [ successEmbed( - `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`, + deleteChannel + ? `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.` + : `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon reste consultable, mais plus personne ne peut y écrire.`, ), ], }); @@ -255,7 +259,15 @@ export async function closeTicket(interaction, reason = null) { ); const channel = interaction.channel; - setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); + if (deleteChannel) { + setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); + return; + } + + // Archived instead of deleted: the author keeps read access, nobody can write. + await channel?.permissionOverwrites + .edit(ticket.author_id, { SendMessages: false }) + .catch(() => log.debug('Could not lock the closed ticket channel', { ticketId: ticket.id })); } /** Grants a staff member access to the ticket channel (M6-T07). */ diff --git a/src/web/api/settings.js b/src/web/api/settings.js index f1ab86a..c6a5fcb 100644 --- a/src/web/api/settings.js +++ b/src/web/api/settings.js @@ -11,7 +11,7 @@ import { env } from '../../config/env.js'; import { createLogger } from '../../core/logger.js'; import { getDatabase } from '../../database/index.js'; import { logEvent, purgeEventsOlderThan } from '../../database/repositories/event-log-repository.js'; -import { getSetting, setSetting } from '../../database/repositories/settings-repository.js'; +import { GUILD_SETTINGS, SETTING_SECTIONS, allSettings, writeSetting } from '../../config/guild-settings.js'; import { createApiToken, deleteSession, @@ -31,76 +31,21 @@ import { isOauthConfigured, redirectUri } from '../auth/discord-oauth.js'; const log = createLogger('web:settings'); const guildId = () => env.discord.guildId; -/** Guild settings the dashboard exposes as first-class switches. */ -const MANAGED_SETTINGS = Object.freeze([ - { - key: 'welcome.enabled', - label: 'Message de bienvenue', - help: 'Publier un message dans le salon d’accueil à chaque arrivée.', - type: 'bool', - default: true, - }, - { - key: 'welcome.directMessage', - label: 'Message privé de bienvenue', - help: 'Envoyer en plus un message privé au nouveau membre.', - type: 'bool', - default: false, - }, - { - key: 'departure.announce', - label: 'Annoncer les départs', - help: 'Publier une ligne dans les logs quand un membre quitte le serveur.', - type: 'bool', - default: true, - }, - { - key: 'moderation.dmTarget', - label: 'Prévenir le membre sanctionné', - help: 'Envoyer un message privé expliquant la sanction et son motif.', - type: 'bool', - default: true, - }, - { - key: 'tickets.autoClaim', - label: 'Prise en charge automatique', - help: 'Attribuer le ticket à la première personne du staff qui y écrit.', - type: 'bool', - default: false, - }, - { - key: 'deploy.requireConfirmation', - label: 'Confirmation avant déploiement', - help: 'Demander de retaper le nom de l’environnement avant de lancer un déploiement.', - type: 'bool', - default: true, - }, - { - key: 'web.defaultMode', - label: 'Mode d’affichage par défaut', - help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages).', - type: 'enum', - options: ['simple', 'advanced'], - default: 'simple', - }, -]); - -const readManaged = () => - Object.fromEntries( - MANAGED_SETTINGS.map((setting) => { - try { - return [setting.key, getSetting(guildId(), setting.key, setting.default)]; - } catch { - return [setting.key, setting.default]; - } - }), - ); +const readManaged = () => { + try { + return allSettings(guildId()); + } catch { + // The database is not ready: fall back to the declared defaults. + return Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting.default])); + } +}; export function registerSettingsRoutes(router) { router.get( '/api/settings', ({ request, actor }) => ({ - schema: MANAGED_SETTINGS, + schema: GUILD_SETTINGS, + sections: SETTING_SECTIONS, values: readManaged(), runtime: { nodeEnv: env.nodeEnv, @@ -166,25 +111,22 @@ export function registerSettingsRoutes(router) { router.put( '/api/settings/values/:key', ({ params, body, actor }) => { - const schema = MANAGED_SETTINGS.find((setting) => setting.key === params.key); - if (!schema) throw notFound('Réglage inconnu.'); + if (!GUILD_SETTINGS.some((setting) => setting.key === params.key)) throw notFound('Réglage inconnu.'); - let value = body.value; - if (schema.type === 'bool') value = Boolean(value); - else if (schema.type === 'enum') { - value = String(value); - if (!schema.options.includes(value)) - throw badRequest(`Valeurs possibles : ${schema.options.join(', ')}.`); + let value; + try { + value = writeSetting(params.key, body.value, { guildId: guildId(), updatedBy: actor.userId }); + } catch (error) { + throw badRequest(error.message); } - setSetting(guildId(), schema.key, value, actor.userId); logEvent({ guildId: guildId(), type: 'web.settings.update', actorId: actor.userId, - payload: { key: schema.key, value }, + payload: { key: params.key, value }, }); - return { key: schema.key, value }; + return { key: params.key, value }; }, { access: ACCESS_LEVELS.DEV }, ); diff --git a/src/web/public/views/settings.js b/src/web/public/views/settings.js index 944126c..3df5afc 100644 --- a/src/web/public/views/settings.js +++ b/src/web/public/views/settings.js @@ -33,47 +33,91 @@ const keyValue = (rows) => rows, ); -function behaviourCard(data, level, reload) { - if (level < LEVELS.DEV) { - return card( - 'Comportement du bot', - { subtitle: 'Lecture seule : le niveau Dev est requis pour modifier ces réglages.' }, - keyValue( - data.schema.map((setting) => ({ - label: setting.label, - value: String(data.values[setting.key]), - })), - ), +/** One control per setting, typed after its declaration. */ +function settingControl(setting, value, apply) { + if (setting.type === 'bool') { + return h( + 'div', + {}, + toggle(Boolean(value), apply, setting.label), + h('div', { class: 'field-help', text: setting.help }), ); } - return card( - 'Comportement du bot', - { subtitle: 'Appliqué immédiatement, sans redémarrage.' }, - ...data.schema.map((setting) => { - const apply = async (value) => { - await api.put(`/api/settings/values/${setting.key}`, { value }); - toast(`« ${setting.label} » enregistré.`); - }; + if (setting.type === 'enum') { + return field( + setting.label, + select( + setting.options.map((option) => ({ value: option, label: option })), + { value, onChange: (event) => apply(event.target.value) }, + ), + { help: setting.help }, + ); + } - if (setting.type === 'bool') { - return h( - 'div', - {}, - toggle(Boolean(data.values[setting.key]), apply, setting.label), - h('div', { class: 'field-help', text: setting.help }), - ); - } - return field( - setting.label, - select( - setting.options.map((option) => ({ value: option, label: option })), - { value: data.values[setting.key], onChange: (event) => apply(event.target.value) }, - ), - { help: setting.help }, + const control = input({ + value: value ?? '', + type: setting.type === 'int' ? 'number' : 'text', + min: setting.min, + max: setting.max, + maxlength: setting.maxLength, + placeholder: String(setting.default ?? ''), + }); + + // Text fields save on blur rather than on every keystroke. + const commit = () => apply(setting.type === 'int' ? Number(control.value) : control.value); + control.addEventListener('change', commit); + control.addEventListener('keydown', (event) => { + if (event.key === 'Enter') control.blur(); + }); + + return field(setting.label, control, { help: setting.help }); +} + +function behaviourCard(data, level, reload) { + const editable = level >= LEVELS.DEV; + const sections = data.sections ?? []; + + return h( + 'div', + { class: 'stack' }, + ...sections.map((section) => { + const settings = data.schema.filter((setting) => setting.section === section.id); + if (settings.length === 0) return null; + + return card( + section.title, + { subtitle: section.summary }, + ...settings.map((setting) => { + const value = data.values[setting.key]; + + if (!editable) { + return h( + 'div', + { class: setting.advanced ? 'advanced-only' : '' }, + h('strong', { text: `${setting.label} : ` }), + h('span', { text: String(value) }), + h('div', { class: 'field-help', text: setting.help }), + ); + } + + const apply = async (next) => { + try { + const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next }); + toast(`« ${setting.label} » enregistré.`); + data.values[setting.key] = saved.value; + } catch (error) { + toast(error.message, 'error'); + } + }; + + const node = settingControl(setting, value, apply); + if (setting.advanced) node.classList.add('advanced-only'); + return node; + }), ); }), - button('Recharger', reload, { tone: 'ghost' }), + editable && button('Recharger les réglages', reload, { tone: 'ghost' }), ); } diff --git a/tests/guild-settings.test.js b/tests/guild-settings.test.js new file mode 100644 index 0000000..5239790 --- /dev/null +++ b/tests/guild-settings.test.js @@ -0,0 +1,143 @@ +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { + GUILD_SETTINGS, + SETTING_SECTIONS, + allSettings, + readSetting, + validateSetting, + writeSetting, +} from '../src/config/guild-settings.js'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; + +const GUILD = 'guild-1'; + +describe('settings schema', () => { + it('places every setting in a declared section', () => { + const sections = new Set(SETTING_SECTIONS.map((section) => section.id)); + for (const setting of GUILD_SETTINGS) { + assert.ok(sections.has(setting.section), `${setting.key} points at an unknown section`); + } + }); + + it('documents every setting and gives it a default', () => { + for (const setting of GUILD_SETTINGS) { + assert.ok(setting.label?.length > 0, `${setting.key} has no label`); + assert.ok(setting.help?.length > 0, `${setting.key} has no help`); + assert.notEqual(setting.default, undefined, `${setting.key} has no default`); + } + }); + + it('uses unique keys', () => { + const keys = GUILD_SETTINGS.map((setting) => setting.key); + assert.equal(new Set(keys).size, keys.length); + }); + + /** + * A switch that nothing reads is worse than no switch: it promises a + * behaviour the bot does not have. + */ + it('is read by the code for every key it declares', async () => { + const { readFile, readdir } = await import('node:fs/promises'); + const path = await import('node:path'); + + const files = []; + const walk = async (directory) => { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) await walk(target); + else if (entry.name.endsWith('.js')) files.push(target); + } + }; + await walk('src'); + + const sources = (await Promise.all(files.map((file) => readFile(file, 'utf8')))).join('\n'); + for (const setting of GUILD_SETTINGS) { + assert.ok( + sources.includes(`'${setting.key}'`), + `${setting.key} is declared but never read by the code`, + ); + } + }); +}); + +describe('settings validation', () => { + it('accepts a boolean and refuses anything else', () => { + assert.equal(validateSetting('welcome.enabled', true), null); + assert.match(validateSetting('welcome.enabled', 'oui'), /vrai ou faux/); + }); + + it('enforces the numeric bounds', () => { + assert.equal(validateSetting('moderation.defaultMuteMinutes', 30), null); + assert.match(validateSetting('moderation.defaultMuteMinutes', 0), /Minimum/); + assert.match(validateSetting('moderation.banDeleteMessageHours', 200), /Maximum/); + assert.match(validateSetting('moderation.defaultMuteMinutes', 'beaucoup'), /entier/); + }); + + it('restricts an enum to its options', () => { + assert.equal(validateSetting('web.defaultMode', 'advanced'), null); + assert.match(validateSetting('web.defaultMode', 'expert'), /Valeurs possibles/); + }); + + it('accepts an empty snowflake, meaning « none »', () => { + assert.equal(validateSetting('notifications.mentionRoleId', ''), null); + assert.equal(validateSetting('notifications.mentionRoleId', '123456789012345678'), null); + assert.match(validateSetting('notifications.mentionRoleId', 'abc'), /17 à 20 chiffres/); + }); + + it('caps the length of a free text', () => { + assert.equal(validateSetting('welcome.message', 'Bonjour'), null); + assert.match(validateSetting('welcome.message', 'x'.repeat(501)), /500 caractères/); + }); + + it('rejects an unknown key', () => { + assert.match(validateSetting('nope', true), /inconnu/); + }); +}); + +describe('settings storage', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM guild_settings;')); + + it('falls back to the declared default', () => { + assert.equal(readSetting('welcome.enabled', GUILD), true); + assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 60); + assert.equal(readSetting('notifications.mentionRoleId', GUILD), ''); + }); + + it('stores then reads a value back with its type', () => { + writeSetting('welcome.enabled', false, { guildId: GUILD }); + writeSetting('moderation.defaultMuteMinutes', 15, { guildId: GUILD }); + + assert.equal(readSetting('welcome.enabled', GUILD), false); + assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 15); + }); + + it('refuses to store an invalid value', () => { + assert.throws(() => writeSetting('web.defaultMode', 'expert', { guildId: GUILD }), /Valeurs possibles/); + assert.equal(readSetting('web.defaultMode', GUILD), 'simple'); + }); + + it('keeps each guild apart', () => { + writeSetting('welcome.enabled', false, { guildId: GUILD }); + assert.equal(readSetting('welcome.enabled', 'other-guild'), true); + }); + + it('coerces a value stored out of bounds back into range', () => { + getDatabase() + .prepare('INSERT INTO guild_settings (guild_id, key, value) VALUES (?, ?, ?)') + .run(GUILD, 'moderation.defaultMuteMinutes', '999999'); + assert.equal(readSetting('moderation.defaultMuteMinutes', GUILD), 40_320); + }); + + it('returns every setting at once', () => { + const values = allSettings(GUILD); + assert.equal(Object.keys(values).length, GUILD_SETTINGS.length); + assert.equal(values['welcome.enabled'], true); + }); + + it('rejects an unknown key rather than storing it', () => { + assert.throws(() => writeSetting('nope', true, { guildId: GUILD }), /Unknown guild setting/); + }); +}); From b42fb1065a0eb0a56b97ce87da75d442f955e304 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:23 +0200 Subject: [PATCH 22/51] feat(voice): take back the generated channels the database forgot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A voice channel outlives the process that made it. A restored backup, a wiped `data/` folder or a redeployment shipping a fresh database all leave real channels behind that nothing manages any more: they are never cleaned up, and their owner can no longer rename or lock them. At startup the bot now reclaims the channels sitting in a trigger's own category and named after its template — a channel created by hand is never touched. Those still in use go back to whoever is inside; the empty ones are leftovers and are removed. Co-Authored-By: Claude Opus 5 (1M context) --- src/events/client-ready.js | 11 +++- src/services/voice/voice-service.js | 85 +++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/src/events/client-ready.js b/src/events/client-ready.js index 964e69a..1bb0d4b 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -2,7 +2,11 @@ import { Events } from 'discord.js'; import { createLogger } from '../core/logger.js'; import { startPollScheduler } from '../services/polls/poll-service.js'; import { startBotStatusRotation } from '../services/status/bot-status-service.js'; -import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js'; +import { + adoptOrphanVoiceChannels, + startVoiceJanitor, + sweepVoiceChannels, +} from '../services/voice/voice-service.js'; const log = createLogger('discord'); @@ -11,6 +15,11 @@ export const once = true; export async function execute(client) { startPollScheduler(client); + // Channels outlive the process: take back the ones the database forgot before + // the sweep decides they are not ours. + await adoptOrphanVoiceChannels(client).catch((error) => + log.warn('Could not recover the orphan voice channels', error), + ); await sweepVoiceChannels(client); startVoiceJanitor(client); startBotStatusRotation(client); diff --git a/src/services/voice/voice-service.js b/src/services/voice/voice-service.js index 344a892..97a03e8 100644 --- a/src/services/voice/voice-service.js +++ b/src/services/voice/voice-service.js @@ -9,6 +9,7 @@ import { } from 'discord.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { readSetting } from '../../config/guild-settings.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.js'; import { getAccessLevel } from '../../core/permissions.js'; @@ -525,6 +526,90 @@ export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GR * (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast * path, this sweep is the guarantee when an event is missed or a deletion failed. */ +/** Builds a matcher from a trigger template, `{user}` standing for any name. */ +function templateMatcher(template) { + const escaped = String(template ?? DEFAULT_TEMPLATE).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return new RegExp(`^${escaped.replace('\\{user\\}', '.+')}$`, 'u'); +} + +/** + * Takes back the generated channels the database no longer knows about (M14-T09). + * + * A channel outlives the process that made it: a restored backup, a wiped + * `data/` folder or a redeployment that ships a fresh database all leave real + * channels behind that nothing manages any more — they never get cleaned up and + * their owner can no longer rename or lock them. + * + * Only channels sitting in a trigger's own category and named after its + * template are taken, so a channel created by hand is never touched. + */ +export async function adoptOrphanVoiceChannels(client) { + let adopted = 0; + let removed = 0; + + for (const guild of client.guilds.cache.values()) { + if (!readSetting('voice.adoptOrphans', guild.id)) continue; + + let triggers = []; + try { + triggers = getVoiceTriggers(guild.id).filter((trigger) => trigger.enabled); + } catch (error) { + log.warn('Could not read the voice triggers', error); + continue; + } + if (triggers.length === 0) continue; + + await guild.channels.fetch().catch(() => null); + + for (const trigger of triggers) { + const triggerChannel = guild.channels.cache.get(trigger.triggerId); + const categoryId = trigger.categoryId || triggerChannel?.parentId; + if (!categoryId) continue; + + const matches = templateMatcher(trigger.template); + + for (const channel of guild.channels.cache.values()) { + if (channel.type !== ChannelType.GuildVoice) continue; + if (channel.parentId !== categoryId) continue; + if (channel.id === trigger.triggerId) continue; + if (getVoiceChannel(channel.id)) continue; + if (!matches.test(channel.name)) continue; + + // Nobody left in it: it is a leftover, not something to hand back. + if (channel.members.size === 0) { + if (await deleteVoiceChannel(channel, 'Salon vocal temporaire orphelin et vide')) { + removed += 1; + logEvent({ guildId: guild.id, type: 'voice.orphan.removed', payload: { channelId: channel.id } }); + } + continue; + } + + // Still in use: give it back to whoever is in it, oldest member first. + const owner = channel.members.filter((member) => !member.user.bot).first() ?? channel.members.first(); + addVoiceChannel({ + channelId: channel.id, + guildId: guild.id, + ownerId: owner.id, + triggerId: trigger.triggerId, + name: channel.name, + userLimit: channel.userLimit ?? 0, + }); + adopted += 1; + logEvent({ + guildId: guild.id, + type: 'voice.orphan.adopted', + payload: { channelId: channel.id, ownerId: owner.id }, + }); + } + } + } + + if (adopted > 0 || removed > 0) { + log.info('Recovered orphan voice channels', { adopted, removed }); + } + return { adopted, removed }; +} + export async function sweepVoiceChannels(client) { for (const guild of client.guilds.cache.values()) { let rows = []; From 262274473a70950b4ab0e5ca946066a5fffdf2e1 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:34 +0200 Subject: [PATCH 23/51] feat(web): publish the slash commands from the panel Registering the commands was the one routine step that still needed shell access on the host, which is awkward when the bot runs behind a hosting panel. Guild commands take effect immediately, so the button says what it did as soon as it returns. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/api/discord.js | 42 ++++++++++++++++++++++++++++++++- src/web/public/views/discord.js | 29 +++++++++++++++++++++-- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/web/api/discord.js b/src/web/api/discord.js index 2153c41..07e3add 100644 --- a/src/web/api/discord.js +++ b/src/web/api/discord.js @@ -1,6 +1,7 @@ -import { ChannelType } from 'discord.js'; +import { ChannelType, REST, Routes } from 'discord.js'; import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js'; import { env } from '../../config/env.js'; +import { ExternalApiError } from '../../core/errors.js'; import { createLogger } from '../../core/logger.js'; import { canActOn, getAccessLevel } from '../../core/permissions.js'; import { logEvent } from '../../database/repositories/event-log-repository.js'; @@ -336,6 +337,45 @@ export function registerDiscordRoutes(router) { { access: ACCESS_LEVELS.STAFF }, ); + /** + * Publishes the slash commands on the guild, what `npm run deploy:commands` + * does. Guild commands take effect immediately, so the result is visible in + * Discord as soon as this returns. + */ + router.post( + '/api/discord/commands/deploy', + async ({ context, actor }) => { + const commands = [...(context.client?.commands?.values() ?? [])]; + if (commands.length === 0) throw badRequest('Aucune commande chargée : le bot n’est pas prêt.'); + if (!env.discord.token || !env.discord.clientId || !env.discord.guildId) { + throw badRequest('`DISCORD_TOKEN`, `DISCORD_CLIENT_ID` et `DISCORD_GUILD_ID` sont requis.'); + } + + const body = commands.map((command) => command.data.toJSON()); + const rest = new REST().setToken(env.discord.token); + + try { + await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { + body, + }); + } catch (error) { + log.error('Slash command deployment failed', error); + throw new ExternalApiError('discord', error.message ?? 'Publication refusée par Discord'); + } + + logEvent({ + guildId: guildId(), + type: 'web.commands.deploy', + actorId: actor.userId, + payload: { count: body.length }, + }); + log.info('Slash commands deployed from the dashboard', { count: body.length, actor: actor.userId }); + + return { ok: true, count: body.length, names: body.map((command) => command.name).sort() }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); + /** Read-only inventory of the loaded slash commands and their required level. */ router.get( '/api/discord/commands', diff --git a/src/web/public/views/discord.js b/src/web/public/views/discord.js index 97356b1..c386cde 100644 --- a/src/web/public/views/discord.js +++ b/src/web/public/views/discord.js @@ -4,6 +4,7 @@ import { badge, button, card, + confirmAction, field, grid, input, @@ -397,8 +398,32 @@ export async function render(host, { state }) { notificationsCard(guild, level), card( - 'Commandes', - { advanced: true, subtitle: 'Commandes slash chargées et niveau requis.' }, + 'Commandes slash', + { + subtitle: 'Commandes chargées par le bot et niveau requis pour chacune.', + actions: + level >= LEVELS.OWNER && + button( + 'Publier sur Discord', + async () => { + if ( + !(await confirmAction( + 'Publier les commandes', + 'Les commandes chargées remplacent celles enregistrées sur le serveur. L’effet est immédiat.', + )) + ) { + return; + } + const result = await api.post('/api/discord/commands/deploy', {}); + toast(`${result.count} commande(s) publiée(s) sur le serveur.`); + }, + { tone: 'primary' }, + ), + }, + h('p', { + class: 'muted', + text: 'À relancer après chaque ajout ou modification de commande — l’équivalent de `npm run deploy:commands`.', + }), await renderCommands(), ), ), From e397abcfcd09e2bf2335922adc3872168b9db225 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:34 +0200 Subject: [PATCH 24/51] fix(web): make the whole repository card open the repository Only the name was a link, so most of a rectangle that reacts to the pointer led nowhere. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/views/repositories.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/web/public/views/repositories.js b/src/web/public/views/repositories.js index 59a7510..ff3ef7a 100644 --- a/src/web/public/views/repositories.js +++ b/src/web/public/views/repositories.js @@ -28,10 +28,12 @@ const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; // --- List ------------------------------------------------------------------- function repositoryCard(repository) { + // The card is the link: clicking anywhere on it opens the repository, which + // is what a rectangle that reacts to the pointer promises. return h( - 'article', - { class: 'repo-card' }, - h('h3', {}, h('a', { href: `#/repos/${repository.fullName}`, text: repository.name })), + 'a', + { class: 'repo-card', href: `#/repos/${repository.fullName}` }, + h('h3', { text: repository.name }), h('p', { class: 'muted', text: repository.description || 'Sans description.' }), h( 'div', From 621f3e404b5cac1ab968a5b7406f64f0adfaf444 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:34 +0200 Subject: [PATCH 25/51] style(web): adopt the official FWS mark and its palette MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The placeholder mark was an Arch-blue chevron. The site now carries the FWS logo — cyan ring on dark navy — and its accent colour follows, so the dashboard and the brand no longer disagree. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/favicon.svg | 32 +++++++++++++++++++--- src/web/public/styles.css | 55 +++++++++++++++++++++++++++----------- 2 files changed, 68 insertions(+), 19 deletions(-) diff --git a/src/web/public/favicon.svg b/src/web/public/favicon.svg index 928aab8..972855a 100644 --- a/src/web/public/favicon.svg +++ b/src/web/public/favicon.svg @@ -1,5 +1,29 @@ - - - - + + FWS Linux + + + + + FWS + + + Linux + diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 3fd602c..0b0dbdd 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -1,21 +1,22 @@ /* FWS-Bot dashboard — Arch blue on a calm dark surface (M16-T11). */ :root { - --blue: #1793d1; - --blue-soft: #8fd3ff; + /* Official FWS mark: cyan ring on dark navy. */ + --blue: #22d3ee; + --blue-soft: #7fe7f8; --green: #2ecc71; --amber: #f1c40f; --red: #e74c3c; --violet: #9b59b6; --gitea: #609926; - --bg: #0b1016; - --bg-elevated: #121a24; - --bg-sunken: #080d12; - --surface: #16202c; - --border: #23303f; - --text: #e6edf3; - --text-muted: #8da2b6; + --bg: #10141f; + --bg-elevated: #171c2b; + --bg-sunken: #0c1018; + --surface: #1b2130; + --border: #2a3145; + --text: #e6ebf3; + --text-muted: #8f98ad; --shadow: 0 10px 30px rgb(0 0 0 / 35%); --radius: 12px; @@ -392,7 +393,7 @@ pre code { .btn-primary { background: var(--blue); border-color: var(--blue); - color: #04121c; + color: #0c1018; } .btn-primary:hover:not(:disabled) { filter: brightness(1.1); @@ -496,7 +497,7 @@ pre code { } .toggle input:checked + .toggle-track::after { transform: translateX(16px); - background: #04121c; + background: #0c1018; } .toggle input:focus-visible + .toggle-track { outline: 2px solid var(--blue-soft); @@ -690,6 +691,15 @@ pre code { padding-left: 1.2rem; } +.wiki-preview { + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 0.9rem; + background: var(--bg-sunken); + max-height: 20rem; + overflow-y: auto; +} + .build { font-size: 0.7rem; padding: 0 0.2rem; @@ -777,7 +787,7 @@ body[data-mode='simple'] .advanced-only { } .mode-switch button.active { background: var(--blue); - color: #04121c; + color: #0c1018; } /* --- Login and setup ------------------------------------------------------ */ @@ -854,7 +864,7 @@ body[data-mode='simple'] .advanced-only { .wizard-step.done .dot { background: var(--green); border-color: var(--green); - color: #04121c; + color: #0c1018; } .wizard-step.invalid .dot { background: var(--red); @@ -944,9 +954,24 @@ body[data-mode='simple'] .advanced-only { display: flex; flex-direction: column; gap: 0.45rem; + color: inherit; + text-decoration: none; + cursor: pointer; + transition: + border-color 0.12s ease, + transform 0.12s ease; } -.repo-card h3 a { - color: var(--text); +.repo-card:hover { + border-color: var(--blue); + text-decoration: none; + transform: translateY(-1px); +} +.repo-card:focus-visible { + outline: 2px solid var(--blue); + outline-offset: 2px; +} +.repo-card h3 { + color: var(--blue-soft); } .repo-meta { display: flex; From c76c0b96ebd4145b875625bd447d917b96c6e057 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:46 +0200 Subject: [PATCH 26/51] feat(wiki): serve a public documentation written from the panel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pages live in SQLite and are read without a session: documentation nobody can reach without an account is not documentation. Drafts answer 404 even when their address is guessed, and the site never falls back to the dashboard shell, which would send a visitor to a login screen. The wiki ships with terms of use and a privacy policy written against the revised Swiss LPD, describing table by table what this codebase actually stores. Both are marked protected: they can be rewritten, not deleted, and a deleted one comes back on the next start — a bot that processes personal data must always be able to show its notice. The bracketed details still have to be completed and the whole reviewed; this is a starting point written from the schema, not legal advice. Co-Authored-By: Claude Opus 5 (1M context) --- src/database/migrations/007-wiki.sql | 21 ++ src/database/repositories/wiki-repository.js | 106 ++++++++ src/web/api/index.js | 3 + src/web/api/wiki.js | 209 ++++++++++++++++ src/web/server.js | 16 +- src/web/services/wiki-seed.js | 249 +++++++++++++++++++ 6 files changed, 601 insertions(+), 3 deletions(-) create mode 100644 src/database/migrations/007-wiki.sql create mode 100644 src/database/repositories/wiki-repository.js create mode 100644 src/web/api/wiki.js create mode 100644 src/web/services/wiki-seed.js diff --git a/src/database/migrations/007-wiki.sql b/src/database/migrations/007-wiki.sql new file mode 100644 index 0000000..31c8810 --- /dev/null +++ b/src/database/migrations/007-wiki.sql @@ -0,0 +1,21 @@ +-- Public wiki pages, written from the dashboard and served without a session (M17) + +CREATE TABLE IF NOT EXISTS wiki_pages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + summary TEXT, + content TEXT NOT NULL DEFAULT '', + category TEXT NOT NULL DEFAULT 'Général', + position INTEGER NOT NULL DEFAULT 0, + published INTEGER NOT NULL DEFAULT 0, + -- A legal page is protected from deletion: the bot must always be able to + -- point at its terms and its privacy notice. + protected INTEGER NOT NULL DEFAULT 0, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_by TEXT, + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_wiki_published ON wiki_pages (published, category, position); diff --git a/src/database/repositories/wiki-repository.js b/src/database/repositories/wiki-repository.js new file mode 100644 index 0000000..bbb22a7 --- /dev/null +++ b/src/database/repositories/wiki-repository.js @@ -0,0 +1,106 @@ +import { getDatabase } from '../index.js'; + +/** Public wiki pages (M17). */ + +const parse = (row) => + row ? { ...row, published: Boolean(row.published), protected: Boolean(row.protected) } : null; + +export function createPage({ + slug, + title, + summary = null, + content = '', + category = 'Général', + position = 0, + published = false, + isProtected = false, + createdBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO wiki_pages + (slug, title, summary, content, category, position, published, protected, created_by, updated_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + slug, + title, + summary, + content, + category, + position, + published ? 1 : 0, + isProtected ? 1 : 0, + createdBy, + createdBy, + ); + return getPage(Number(lastInsertRowid)); +} + +export function getPage(id) { + return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE id = ?').get(id) ?? null); +} + +export function getPageBySlug(slug) { + return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE slug = ?').get(slug) ?? null); +} + +/** Published pages only, in reading order — what the public site shows. */ +export function listPublished() { + return getDatabase() + .prepare('SELECT * FROM wiki_pages WHERE published = 1 ORDER BY category, position, title') + .all() + .map(parse); +} + +export function listAllPages() { + return getDatabase() + .prepare('SELECT * FROM wiki_pages ORDER BY category, position, title') + .all() + .map(parse); +} + +const UPDATABLE = Object.freeze({ + slug: (value) => value, + title: (value) => value, + summary: (value) => value, + content: (value) => value, + category: (value) => value, + position: (value) => Number.parseInt(value, 10) || 0, + published: (value) => (value ? 1 : 0), +}); + +export function updatePage(id, patch, updatedBy = null) { + const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE); + if (entries.length === 0) return getPage(id); + + const assignments = entries.map(([key]) => `${key} = ?`).join(', '); + const values = entries.map(([key, value]) => UPDATABLE[key](value)); + getDatabase() + .prepare( + `UPDATE wiki_pages SET ${assignments}, updated_by = ?, updated_at = datetime('now') WHERE id = ?`, + ) + .run(...values, updatedBy, id); + return getPage(id); +} + +export function removePage(id) { + return getDatabase().prepare('DELETE FROM wiki_pages WHERE id = ? AND protected = 0').run(id).changes; +} + +export function countPages() { + return getDatabase().prepare('SELECT COUNT(*) AS count FROM wiki_pages').get().count; +} + +/** Full-text-ish search over the published pages, good enough for a small wiki. */ +export function searchPublished(term) { + const needle = `%${term}%`; + return getDatabase() + .prepare( + `SELECT * FROM wiki_pages + WHERE published = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?) + ORDER BY category, position, title LIMIT 25`, + ) + .all(needle, needle, needle) + .map(parse); +} diff --git a/src/web/api/index.js b/src/web/api/index.js index 2f50d88..8380504 100644 --- a/src/web/api/index.js +++ b/src/web/api/index.js @@ -14,6 +14,7 @@ import { registerOverviewRoutes } from './overview.js'; import { registerReleaseRoutes } from './releases.js'; import { registerRepositoryRoutes } from './repositories.js'; import { registerSettingsRoutes } from './settings.js'; +import { registerWikiRoutes } from './wiki.js'; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -72,6 +73,8 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) { registerAuthRoutes(router); registerConfigurationRoutes(router); + // The public documentation stays reachable even while the bot is being set up. + registerWikiRoutes(router); // Long-lived stream the pages listen to instead of polling (M16-T12). router.get( diff --git a/src/web/api/wiki.js b/src/web/api/wiki.js new file mode 100644 index 0000000..99ebbb8 --- /dev/null +++ b/src/web/api/wiki.js @@ -0,0 +1,209 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + createPage, + getPage, + getPageBySlug, + listAllPages, + listPublished, + removePage, + searchPublished, + updatePage, +} from '../../database/repositories/wiki-repository.js'; +import { badRequest, forbidden, notFound } from '../http.js'; + +/** + * Public wiki, written from the dashboard (M17). + * + * The reading routes are deliberately open: a documentation nobody can reach + * without an account is not documentation. The writing routes sit behind the + * Dev level like the rest of the panel. + */ + +const SLUG = /^[a-z0-9][a-z0-9-]{0,80}$/; + +/** Shown in a listing: everything but the body, which can be long. */ +const summarize = (page) => ({ + slug: page.slug, + title: page.title, + summary: page.summary, + category: page.category, + position: page.position, + updatedAt: page.updated_at, +}); + +const full = (page) => ({ ...summarize(page), content: page.content }); + +const adminView = (page) => ({ + id: page.id, + ...full(page), + published: page.published, + protected: page.protected, + createdBy: page.created_by, + createdAt: page.created_at, + updatedBy: page.updated_by, +}); + +/** Categories in reading order, each with its pages. */ +function tree(pages) { + const categories = []; + for (const page of pages) { + let category = categories.find((entry) => entry.name === page.category); + if (!category) categories.push((category = { name: page.category, pages: [] })); + category.pages.push(summarize(page)); + } + return categories; +} + +export function registerWikiRoutes(router) { + // --- Public ---------------------------------------------------------------- + router.get( + '/api/wiki', + () => { + const pages = listPublished(); + return { + site: { + title: 'Documentation FWS', + links: env.links, + }, + categories: tree(pages), + count: pages.length, + }; + }, + { public: true }, + ); + + router.get( + '/api/wiki/pages/:slug', + ({ params }) => { + const page = getPageBySlug(params.slug); + // A draft must not be readable by guessing its address. + if (!page || !page.published) throw notFound('Page introuvable.'); + return full(page); + }, + { public: true }, + ); + + router.get( + '/api/wiki/search', + ({ query }) => { + const term = (query.get('q') ?? '').trim(); + if (term.length < 2) return { results: [] }; + return { results: searchPublished(term).map(summarize) }; + }, + { public: true }, + ); + + // --- Administration -------------------------------------------------------- + router.get('/api/wiki/admin', () => ({ pages: listAllPages().map(adminView) }), { + access: ACCESS_LEVELS.STAFF, + }); + + router.get( + '/api/wiki/admin/:id', + ({ params }) => { + const page = getPage(Number.parseInt(params.id, 10)); + if (!page) throw notFound('Page introuvable.'); + return adminView(page); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + + router.post( + '/api/wiki/admin', + ({ body, actor }) => { + const slug = String(body.slug ?? '') + .trim() + .toLowerCase(); + if (!SLUG.test(slug)) { + throw badRequest('Adresse invalide : minuscules, chiffres et tirets, 80 caractères maximum.'); + } + if (getPageBySlug(slug)) throw badRequest(`Une page utilise déjà l’adresse « ${slug} ».`); + + const title = String(body.title ?? '').trim(); + if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.'); + + const page = createPage({ + slug, + title, + summary: body.summary ? String(body.summary) : null, + content: String(body.content ?? ''), + category: String(body.category ?? '').trim() || 'Général', + position: Number.parseInt(body.position ?? 0, 10) || 0, + published: Boolean(body.published), + createdBy: actor.userId, + }); + + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.wiki.create', + actorId: actor.userId, + payload: { slug }, + }); + return adminView(page); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.patch( + '/api/wiki/admin/:id', + ({ params, body, actor }) => { + const page = getPage(Number.parseInt(params.id, 10)); + if (!page) throw notFound('Page introuvable.'); + + const patch = {}; + if (body.slug !== undefined) { + const slug = String(body.slug).trim().toLowerCase(); + if (!SLUG.test(slug)) throw badRequest('Adresse invalide.'); + + const clash = getPageBySlug(slug); + if (clash && clash.id !== page.id) throw badRequest(`Une page utilise déjà l’adresse « ${slug} ».`); + patch.slug = slug; + } + if (body.title !== undefined) { + const title = String(body.title).trim(); + if (title.length < 2) throw badRequest('Le titre doit faire au moins 2 caractères.'); + patch.title = title; + } + for (const key of ['summary', 'content', 'category']) { + if (body[key] !== undefined) patch[key] = String(body[key]); + } + if (body.position !== undefined) patch.position = body.position; + if (body.published !== undefined) patch.published = Boolean(body.published); + + if (Object.keys(patch).length === 0) throw badRequest('Aucun champ modifiable fourni.'); + + const updated = updatePage(page.id, patch, actor.userId); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.wiki.update', + actorId: actor.userId, + payload: { slug: updated.slug, fields: Object.keys(patch) }, + }); + return adminView(updated); + }, + { access: ACCESS_LEVELS.DEV }, + ); + + router.delete( + '/api/wiki/admin/:id', + ({ params, actor }) => { + const page = getPage(Number.parseInt(params.id, 10)); + if (!page) throw notFound('Page introuvable.'); + if (page.protected) { + throw forbidden('Cette page est protégée : elle peut être réécrite, mais pas supprimée.'); + } + + removePage(page.id); + logEvent({ + guildId: env.discord.guildId || null, + type: 'web.wiki.delete', + actorId: actor.userId, + payload: { slug: page.slug }, + }); + return { ok: true }; + }, + { access: ACCESS_LEVELS.OWNER }, + ); +} diff --git a/src/web/server.js b/src/web/server.js index 76fda41..9dd2a00 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -11,6 +11,7 @@ import { authorize } from './auth/guard.js'; import { broadcast, closeEventStreams, topicForPath } from './events.js'; import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; import { createRouter } from './router.js'; +import { seedWiki } from './services/wiki-seed.js'; /** HTTP server of the dashboard (M16-T01). */ @@ -71,9 +72,10 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/'); if (!isApi) { - // Anything else is the single page application; unknown paths fall back to - // its shell so client-side routing works on a hard refresh. - const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' }); + // The wiki is a separate public page: it must never fall back to the + // dashboard shell, which would send a visitor to a login screen. + const fallback = pathname === '/wiki' || pathname.startsWith('/wiki/') ? 'wiki.html' : 'index.html'; + const served = await sendStatic(response, publicDir, pathname, { fallback }); if (!served) sendEmpty(response, 404); return; } @@ -128,6 +130,14 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da } export function startWebServer({ client = null, setupOnly = false } = {}) { + // A bot that processes personal data owes its users a notice, so the legal + // pages are created before the site answers its first request. + try { + seedWiki(); + } catch (error) { + log.warn('Could not seed the wiki', error); + } + const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() })); server.listen(env.web.port, env.web.host, () => { diff --git a/src/web/services/wiki-seed.js b/src/web/services/wiki-seed.js new file mode 100644 index 0000000..0368d2d --- /dev/null +++ b/src/web/services/wiki-seed.js @@ -0,0 +1,249 @@ +import { createLogger } from '../../core/logger.js'; +import { countPages, createPage, getPageBySlug } from '../../database/repositories/wiki-repository.js'; + +/** + * Pages the wiki ships with (M17). + * + * The two legal ones are seeded because a bot that processes personal data owes + * its users a notice, and an empty wiki makes that easy to forget. They are + * marked `protected`, so they can be rewritten but not deleted by accident. + * + * They describe what this codebase actually stores — nothing aspirational — but + * the organisation still has to fill in the bracketed details and have them + * reviewed. This is a starting point written from the schema, not legal advice. + */ + +const log = createLogger('wiki'); + +const TERMS = `## 1. Objet + +Ces conditions régissent l'utilisation du bot Discord **FWS-Bot** et de son tableau de bord, exploités par **[NOM DE L'ENTITÉ RESPONSABLE]** (ci-après « nous »). + +Utiliser le bot — une commande, un ticket, un sondage, un salon vocal généré — vaut acceptation de ces conditions. Si tu n'en acceptes pas les termes, n'utilise pas le bot. + +## 2. Service fourni + +Le bot propose de l'assistance communautaire, des tickets de support, de la modération, des sondages, des salons vocaux temporaires et une intégration avec notre forge Gitea. + +Le service est fourni **en l'état**, gratuitement et sans garantie de disponibilité. Nous pouvons le modifier, l'interrompre ou l'arrêter à tout moment, notamment pour maintenance ou pour des raisons de sécurité. + +## 3. Règles d'utilisation + +En utilisant le bot, tu t'engages à : + +- respecter le règlement du serveur Discord ainsi que les [Conditions d'utilisation de Discord](https://discord.com/terms) ; +- ne pas tenter d'accéder à des fonctions réservées à l'équipe, ni de contourner les contrôles d'accès ; +- ne pas automatiser, surcharger ou perturber le service ; +- ne pas publier, via le bot, de contenu illicite, haineux, diffamatoire ou portant atteinte aux droits de tiers ; +- ne pas utiliser les tickets pour transmettre des données sensibles au sens de l'art. 5 let. c LPD (santé, opinions religieuses ou politiques, données biométriques, etc.). + +## 4. Modération + +L'équipe peut avertir, exclure temporairement, expulser ou bannir un compte qui ne respecte pas ces règles. Les sanctions sont consignées et consultables par l'équipe. Tu peux contester une sanction en ouvrant un ticket ou en écrivant à l'adresse indiquée au point 8. + +## 5. Contenus que tu publies + +Tu restes titulaire de ce que tu écris. Tu nous accordes le droit d'afficher, de stocker et de traiter ces contenus dans la stricte mesure nécessaire au fonctionnement du service. + +## 6. Responsabilité + +Dans les limites permises par le droit suisse, notre responsabilité est exclue pour les dommages indirects, la perte de données et l'indisponibilité du service. Rien dans ces conditions n'exclut la responsabilité en cas de faute intentionnelle ou de négligence grave. + +Le bot dépend de services tiers (Discord, notre instance Gitea, l'hébergeur). Nous ne répondons pas de leurs interruptions. + +## 7. Modification des conditions + +Nous pouvons modifier ces conditions. La version applicable est celle publiée sur cette page ; les changements importants sont annoncés sur le serveur Discord. Continuer d'utiliser le bot après une modification vaut acceptation. + +## 8. Droit applicable et contact + +Ces conditions sont soumises au **droit suisse**. Le for est à **[LIEU DU SIÈGE]**, sous réserve des fors impératifs. + +Contact : **[ADRESSE DE CONTACT]** + +_Dernière mise à jour : à compléter lors de la première relecture._ +`; + +const PRIVACY = `Cette politique explique quelles données personnelles le bot traite, pourquoi, et quels droits tu as. Elle est rédigée conformément à la **loi fédérale sur la protection des données (LPD, RS 235.1)** révisée, en vigueur depuis le 1er septembre 2023, et à son ordonnance (OPDo). + +## 1. Responsable du traitement + +**[NOM DE L'ENTITÉ RESPONSABLE]** +[ADRESSE POSTALE] +[ADRESSE DE CONTACT] + +Nous n'avons pas désigné de conseiller à la protection des données au sens de l'art. 10 LPD ; les demandes sont traitées à l'adresse ci-dessus. + +## 2. Données traitées + +Le bot ne collecte que ce dont il a besoin pour fonctionner. Concrètement : + +### Sur Discord + +| Donnée | Quand | Pourquoi | +| --- | --- | --- | +| Identifiant Discord, pseudo, nom affiché, avatar | À chaque interaction | Identifier l'auteur d'une action et afficher un nom lisible | +| Identifiants de serveur, de salon et de rôles | En continu | Appliquer les droits et publier au bon endroit | +| Tickets : catégorie, auteur, personne en charge, dates, motif de clôture | À l'ouverture et à la clôture | Assurer le suivi du support | +| Sanctions : type, personne visée, personne qui sanctionne, motif, durée | À chaque sanction | Tenir un historique de modération et traiter les contestations | +| Sondages : question, choix, et **le vote de chaque personne** | À chaque vote | Compter les voix et empêcher les votes multiples | +| Salons vocaux générés : propriétaire, nom, verrouillage, limite | Tant que le salon existe | Rendre la personne maîtresse de son salon | +| Journal d'événements : type d'action, auteur, horodatage | À chaque action notable | Traçabilité, sécurité, diagnostic | + +### Sur le tableau de bord + +| Donnée | Quand | Pourquoi | +| --- | --- | --- | +| Identifiant, pseudo, nom affiché, avatar Discord | À la connexion | Authentifier et afficher qui est connecté | +| Rôles sur le serveur | À la connexion | Déterminer le niveau d'accès | +| Adresse IP et agent utilisateur | Pendant la session | Sécurité, détection d'un accès anormal | +| Empreinte du jeton de session | Pendant la session | Maintenir la connexion sans stocker le jeton lui-même | + +### Ce que nous ne traitons pas + +- **Le contenu de tes messages Discord** : le bot ne demande pas l'autorisation \`Message Content\` et ne lit donc pas tes messages. +- **Aucune donnée sensible** au sens de l'art. 5 let. c LPD n'est collectée volontairement. Merci de ne pas en transmettre dans un ticket. +- **Aucun profilage** et **aucune décision individuelle automatisée** au sens de l'art. 21 LPD : toute sanction est décidée par une personne. + +## 3. Finalités + +Les traitements servent exclusivement à : faire fonctionner le service, modérer la communauté, assurer le support, garantir la sécurité du système, et diagnostiquer les incidents. + +Il n'y a **ni publicité, ni revente, ni transmission commerciale** de données. + +## 4. Base du traitement + +Le traitement repose sur l'exécution du service que tu demandes en utilisant le bot, ainsi que sur notre intérêt légitime à sécuriser et modérer la communauté (art. 31 LPD). Lorsqu'un consentement est requis, il est demandé explicitement. + +## 5. Destinataires et sous-traitants + +| Destinataire | Rôle | Localisation | +| --- | --- | --- | +| Discord Inc. | Plateforme sur laquelle le bot fonctionne | États-Unis | +| [HÉBERGEUR] | Hébergement du bot et de sa base de données | [PAYS] | +| Notre instance Gitea | Issues, pull requests, releases | [PAYS] | + +Aucune donnée n'est transmise à d'autres tiers, sauf obligation légale. + +## 6. Communication à l'étranger + +Discord traite des données aux **États-Unis**. Cette communication a lieu conformément aux art. 16 et 17 LPD, sur la base des garanties contractuelles et des décisions d'adéquation applicables. En utilisant Discord, tu es de toute façon déjà soumis à sa propre [politique de confidentialité](https://discord.com/privacy). + +## 7. Durée de conservation + +| Donnée | Conservation | +| --- | --- | +| Journal d'événements | Purgé automatiquement selon \`LOG_RETENTION_DAYS\` (30 jours par défaut) | +| Sessions du tableau de bord | Expirent automatiquement, 12 heures par défaut | +| Tickets | Conservés pour le suivi, effaçables sur demande | +| Sanctions | Conservées tant qu'elles restent pertinentes pour la modération | +| Salons vocaux | Supprimés en même temps que le salon | +| Journaux techniques | Fichiers quotidiens, purgés selon la même durée de rétention | + +## 8. Sécurité + +Conformément à l'art. 8 LPD, nous prenons des mesures techniques et organisationnelles appropriées : + +- accès au tableau de bord restreint aux rôles Staff, Dev et Owner du serveur ; +- jetons de session et jetons d'API stockés sous forme d'empreinte, jamais en clair ; +- secrets masqués automatiquement dans les journaux ; +- webhooks signés en HMAC-SHA256 et vérifiés à temps constant ; +- base de données locale, non exposée publiquement, sauvegardable. + +## 9. Tes droits + +Selon la LPD, tu peux à tout moment : + +- **demander l'accès** à tes données (art. 25 LPD) ; +- **faire rectifier** une donnée inexacte (art. 32 LPD) ; +- **demander l'effacement** de tes données, sous réserve de ce que nous devons conserver ; +- **t'opposer** à un traitement ; +- **obtenir la remise** de tes données dans un format courant (art. 28 LPD). + +Écris à **[ADRESSE DE CONTACT]** ou ouvre un ticket. Nous répondons en principe dans les 30 jours. La demande est gratuite ; une pièce d'identité peut être demandée en cas de doute sérieux sur ton identité. + +Tu peux aussi t'adresser au **Préposé fédéral à la protection des données et à la transparence (PFPDT)**, Feldeggweg 1, 3003 Berne — [edoeb.admin.ch](https://www.edoeb.admin.ch). + +## 10. Violations de données + +En cas de violation de la sécurité entraînant un risque élevé pour tes droits, nous annonçons l'incident au PFPDT dans les meilleurs délais (art. 24 LPD) et t'informons lorsque la loi l'exige. + +## 11. Modifications + +Cette politique peut évoluer. La version applicable est celle publiée ici, et les changements importants sont annoncés sur le serveur Discord. + +_Dernière mise à jour : à compléter lors de la première relecture._ + +--- + +> ⚠️ **À faire relire.** Ce texte décrit fidèlement ce que le code traite, mais les mentions entre crochets doivent être complétées et l'ensemble validé par une personne compétente avant publication. +`; + +const WELCOME = `Bienvenue sur la documentation publique de **FWS**. + +Ces pages sont rédigées et publiées depuis le tableau de bord du bot : elles n'ont besoin d'aucun dépôt séparé ni d'aucune étape de compilation. + +## Pour commencer + +- **Conditions d'utilisation** — ce à quoi tu t'engages en utilisant le bot. +- **Politique de confidentialité** — quelles données sont traitées, pourquoi, et tes droits. + +## Contribuer + +Cette documentation est modifiable par l'équipe depuis **Tableau de bord → Wiki**. Une page peut rester en brouillon le temps d'être écrite, puis être publiée en un clic. +`; + +/** Pages created on first start, and re-created if a protected one goes missing. */ +const DEFAULT_PAGES = [ + { + slug: 'accueil', + title: 'Accueil', + summary: 'Point d’entrée de la documentation publique FWS.', + category: 'Général', + position: 0, + content: WELCOME, + published: true, + isProtected: false, + }, + { + slug: 'conditions-utilisation', + title: 'Conditions d’utilisation', + summary: 'Ce à quoi tu t’engages en utilisant le bot FWS.', + category: 'Légal', + position: 10, + content: TERMS, + published: true, + isProtected: true, + }, + { + slug: 'politique-confidentialite', + title: 'Politique de confidentialité', + summary: 'Données traitées, durées de conservation et droits, selon la LPD suisse.', + category: 'Légal', + position: 20, + content: PRIVACY, + published: true, + isProtected: true, + }, +]; + +/** + * Creates the default pages when they are missing. + * Existing pages are never overwritten: the organisation's own wording wins. + */ +export function seedWiki() { + let created = 0; + + for (const page of DEFAULT_PAGES) { + // The welcome page is only offered on a genuinely empty wiki; the legal ones + // come back whenever they are absent. + if (!page.isProtected && countPages() > 0) continue; + if (getPageBySlug(page.slug)) continue; + + createPage({ ...page, createdBy: 'system' }); + created += 1; + } + + if (created > 0) log.info('Seeded the wiki with its default pages', { created }); + return created; +} From e5b7303a01ff4b25e41a332deb1977f1aebaa202 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:46 +0200 Subject: [PATCH 27/51] feat(wiki): add the reading site and its editor The renderer escapes HTML before any transformation and drops `javascript:` links. Pages are written by the team, but a renderer that relies on that is one mistake away from being a hole. The editor previews as you type: legal pages are long, and writing Markdown blind is how broken tables end up published. Co-Authored-By: Claude Opus 5 (1M context) --- src/web/public/app.js | 8 ++ src/web/public/core/markdown.js | 168 ++++++++++++++++++++++ src/web/public/views/wiki.js | 240 ++++++++++++++++++++++++++++++++ src/web/public/wiki.css | 198 ++++++++++++++++++++++++++ src/web/public/wiki.html | 19 +++ src/web/public/wiki.js | 183 ++++++++++++++++++++++++ tests/web-wiki.test.js | 215 ++++++++++++++++++++++++++++ 7 files changed, 1031 insertions(+) create mode 100644 src/web/public/core/markdown.js create mode 100644 src/web/public/views/wiki.js create mode 100644 src/web/public/wiki.css create mode 100644 src/web/public/wiki.html create mode 100644 src/web/public/wiki.js create mode 100644 tests/web-wiki.test.js diff --git a/src/web/public/app.js b/src/web/public/app.js index b4f7de5..bb73d99 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -68,6 +68,14 @@ const ROUTES = [ module: './views/community.js', level: LEVELS.STAFF, }, + { + path: 'wiki', + icon: '📖', + label: 'Wiki', + group: 'Communauté', + module: './views/wiki.js', + level: LEVELS.STAFF, + }, { path: 'logs', icon: '≡', diff --git a/src/web/public/core/markdown.js b/src/web/public/core/markdown.js new file mode 100644 index 0000000..3b9d9d5 --- /dev/null +++ b/src/web/public/core/markdown.js @@ -0,0 +1,168 @@ +/** + * Markdown renderer for the wiki (M17). + * + * Deliberately small: headings, lists, tables, code, quotes, links, emphasis. + * Everything is HTML-escaped **before** any transformation runs, so a page can + * never inject markup — the pages are written by the team, but a renderer that + * relies on that is one mistake away from being a hole. + */ + +const escape = (text) => + String(text ?? '') + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +export const slugify = (text) => + String(text) + .toLowerCase() + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + +/** Inline pass, applied to text that is already escaped. */ +function inline(text) { + return text + .replace(/`([^`]+)`/g, '$1') + .replace( + /!\[([^\]]*)\]\(([^)\s]+)\)/g, + (_, alt, src) => `${alt}`, + ) + .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, href) => { + // Only http(s) and in-page anchors: no `javascript:` sneaking through. + const safe = /^(https?:\/\/|\/|#)/.test(href) ? href : '#'; + const external = safe.startsWith('http'); + return `${label}`; + }) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2') + .replace(/~~([^~]+)~~/g, '$1'); +} + +const cells = (line) => + line + .trim() + .replace(/^\||\|$/g, '') + .split('|') + .map((cell) => inline(cell.trim())); + +/** + * Renders a page and returns `{ html, headings }`, the headings feeding the + * table of contents. + */ +export function render(markdown) { + const lines = escape(markdown).split('\n'); + const out = []; + const headings = []; + + let index = 0; + const closeList = (stack) => { + while (stack.length > 0) out.push(``); + }; + const listStack = []; + + while (index < lines.length) { + const line = lines[index]; + + // Fenced code, kept verbatim. + if (/^\s*```/.test(line)) { + closeList(listStack); + const body = []; + index += 1; + while (index < lines.length && !/^\s*```/.test(lines[index])) body.push(lines[index++]); + index += 1; + out.push(`
    ${body.join('\n')}
    `); + continue; + } + + // Table: a header row followed by a separator row. + if (line.includes('|') && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[index + 1] ?? '')) { + closeList(listStack); + const header = cells(line); + index += 2; + + const rows = []; + while (index < lines.length && lines[index].includes('|') && lines[index].trim() !== '') { + rows.push(cells(lines[index++])); + } + out.push( + `
    ${header + .map((cell) => ``) + .join('')}${rows + .map((row) => `${row.map((cell) => ``).join('')}`) + .join('')}
    ${cell}
    ${cell}
    `, + ); + continue; + } + + const heading = /^(#{1,4})\s+(.*)$/.exec(line); + if (heading) { + closeList(listStack); + const level = heading[1].length; + const text = heading[2].trim(); + const id = slugify(text); + if (level <= 3) headings.push({ id, text, level }); + out.push(`${inline(text)}`); + index += 1; + continue; + } + + if (/^\s*(---|\*\*\*)\s*$/.test(line)) { + closeList(listStack); + out.push('
    '); + index += 1; + continue; + } + + const quote = /^>\s?(.*)$/.exec(line); + if (quote) { + closeList(listStack); + const body = [quote[1]]; + index += 1; + while (index < lines.length && /^>\s?/.test(lines[index])) { + body.push(lines[index++].replace(/^>\s?/, '')); + } + out.push(`
    ${inline(body.join(' '))}
    `); + continue; + } + + const bullet = /^\s*[-*]\s+(.*)$/.exec(line); + const ordered = /^\s*\d+\.\s+(.*)$/.exec(line); + if (bullet || ordered) { + const tag = bullet ? 'ul' : 'ol'; + if (listStack.at(-1) !== tag) { + closeList(listStack); + out.push(`<${tag}>`); + listStack.push(tag); + } + out.push(`
  • ${inline((bullet ?? ordered)[1])}
  • `); + index += 1; + continue; + } + + if (line.trim() === '') { + closeList(listStack); + index += 1; + continue; + } + + // Paragraph: consecutive non-empty lines are joined. + closeList(listStack); + const paragraph = [line]; + index += 1; + while ( + index < lines.length && + lines[index].trim() !== '' && + !/^\s*([-*]\s|\d+\.\s|#{1,4}\s|>|```)/.test(lines[index]) && + !lines[index].includes('|') + ) { + paragraph.push(lines[index++]); + } + out.push(`

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

    `); + } + + closeList(listStack); + return { html: out.join('\n'), headings }; +} diff --git a/src/web/public/views/wiki.js b/src/web/public/views/wiki.js new file mode 100644 index 0000000..b82c405 --- /dev/null +++ b/src/web/public/views/wiki.js @@ -0,0 +1,240 @@ +import { api } from '../core/api.js'; +import { formatRelative, h } from '../core/dom.js'; +import { autoRefresh } from '../core/live.js'; +import { render as renderMarkdown } from '../core/markdown.js'; +import { + badge, + button, + card, + confirmAction, + field, + input, + notice, + renderAsync, + table, + textarea, + toast, + toggle, +} from '../core/ui.js'; + +/** Editing the public documentation from the panel (M17). */ + +const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 }; + +const slugify = (text) => + text + .toLowerCase() + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 80); + +/** + * Editor with a live preview: legal pages are long, and writing Markdown blind + * is how broken tables end up published. + */ +async function editPage(existing, reload) { + const title = input({ value: existing?.title ?? '', placeholder: 'Titre de la page' }); + const slug = input({ value: existing?.slug ?? '', placeholder: 'adresse-de-la-page' }); + const summary = input({ value: existing?.summary ?? '', placeholder: 'Une phrase de résumé' }); + const category = input({ value: existing?.category ?? 'Général', placeholder: 'Général' }); + const position = input({ type: 'number', value: existing?.position ?? 0 }); + const content = textarea({ value: existing?.content ?? '', style: { minHeight: '22rem' } }); + let published = existing?.published ?? false; + + // A new page gets its address from its title until the address is touched. + let slugTouched = Boolean(existing); + slug.addEventListener('input', () => (slugTouched = true)); + title.addEventListener('input', () => { + if (!slugTouched) slug.value = slugify(title.value); + }); + + const preview = h('div', { class: 'wiki-content' }); + const refreshPreview = () => { + preview.innerHTML = renderMarkdown(content.value).html; + }; + content.addEventListener('input', refreshPreview); + refreshPreview(); + + const showPreview = h('div', { class: 'wiki-preview' }, preview); + showPreview.hidden = true; + + const { modal } = await import('../core/ui.js'); + const confirmed = await modal( + existing ? `Modifier « ${existing.title} »` : 'Nouvelle page', + () => ({ + node: h( + 'div', + { class: 'stack' }, + field('Titre', title), + field('Adresse', slug, { help: 'Minuscules, chiffres et tirets. Visible dans l’URL : /wiki/…' }), + field('Résumé', summary, { help: 'Affiché sous le titre et dans les résultats de recherche.' }), + field('Catégorie', category, { help: 'Regroupe les pages dans le menu du site public.' }), + field('Position', position, { help: 'Ordre dans la catégorie, du plus petit au plus grand.' }), + field('Contenu (Markdown)', content), + button( + 'Afficher / masquer l’aperçu', + () => { + showPreview.hidden = !showPreview.hidden; + refreshPreview(); + }, + { tone: 'ghost' }, + ), + showPreview, + toggle(published, (checked) => (published = checked), 'Publier (visible par tout le monde)'), + existing?.protected && + notice('Page protégée : son contenu est modifiable, mais elle ne peut pas être supprimée.', 'info'), + ), + submit: () => title.value.trim().length >= 2 && slug.value.trim() !== '', + }), + { confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' }, + ); + if (!confirmed) return; + + const payload = { + title: title.value.trim(), + slug: slug.value.trim(), + summary: summary.value.trim(), + category: category.value.trim() || 'Général', + position: Number(position.value) || 0, + content: content.value, + published, + }; + + try { + if (existing) await api.patch(`/api/wiki/admin/${existing.id}`, payload); + else await api.post('/api/wiki/admin', payload); + toast(existing ? 'Page enregistrée.' : 'Page créée.'); + reload(); + } catch (error) { + toast(error.message, 'error'); + } +} + +export function render(host, { state }) { + const level = state.me.accessLevel; + const reload = () => render(host, { state }); + autoRefresh(reload, { topics: ['mutation'] }); + + return renderAsync( + host, + () => api.get('/api/wiki/admin'), + (data) => { + const published = data.pages.filter((page) => page.published).length; + + return h( + 'div', + { class: 'stack' }, + h( + 'div', + { class: 'page-head' }, + h( + 'div', + {}, + h('h1', { text: 'Wiki' }), + h('p', { + class: 'muted', + text: 'Documentation publique, écrite ici et lisible sans compte sur /wiki.', + }), + ), + h( + 'div', + { class: 'row' }, + h('a', { + class: 'btn btn-ghost', + href: '/wiki', + target: '_blank', + rel: 'noreferrer', + text: '↗ Voir le site', + }), + level >= LEVELS.DEV && button('Nouvelle page', () => editPage(null, reload), { tone: 'primary' }), + ), + ), + + published === 0 && + notice('Aucune page publiée : le site public affichera une documentation vide.', 'warning'), + + card( + 'Pages', + { subtitle: `${data.pages.length} page(s), dont ${published} publiée(s)` }, + table( + [ + { + label: 'Page', + render: (page) => + h( + 'div', + {}, + h('strong', { text: page.title }), + h('div', { class: 'muted', text: page.summary || `/wiki/${page.slug}` }), + ), + }, + { label: 'Catégorie', render: (page) => badge(page.category, 'info') }, + { label: 'Ordre', className: 'num advanced-only', key: 'position' }, + { + label: 'État', + render: (page) => + h( + 'div', + { class: 'row' }, + page.published ? badge('Publiée', 'success') : badge('Brouillon', 'neutral'), + page.protected && badge('Protégée', 'warning'), + ), + }, + { + label: 'Modifiée', + className: 'nowrap', + render: (page) => formatRelative(page.updatedAt), + }, + { + label: '', + render: (page) => + h( + 'div', + { class: 'row' }, + page.published && + h('a', { + class: 'btn btn-ghost btn-sm', + href: `/wiki/${page.slug}`, + target: '_blank', + rel: 'noreferrer', + text: 'Voir', + }), + level >= LEVELS.DEV && + button('Modifier', () => editPage(page, reload), { tone: 'ghost' }), + level >= LEVELS.DEV && + button( + page.published ? 'Dépublier' : 'Publier', + async () => { + await api.patch(`/api/wiki/admin/${page.id}`, { published: !page.published }); + toast(page.published ? 'Page dépubliée.' : 'Page publiée.'); + reload(); + }, + { tone: page.published ? 'ghost' : 'success' }, + ), + level >= LEVELS.OWNER && + !page.protected && + button( + 'Supprimer', + async () => { + if (!(await confirmAction('Supprimer la page', `Supprimer « ${page.title} » ?`))) { + return; + } + await api.delete(`/api/wiki/admin/${page.id}`); + toast('Page supprimée.'); + reload(); + }, + { tone: 'danger' }, + ), + ), + }, + ], + data.pages, + { empty: 'Aucune page.' }, + ), + ), + ); + }, + ); +} diff --git a/src/web/public/wiki.css b/src/web/public/wiki.css new file mode 100644 index 0000000..add65ac --- /dev/null +++ b/src/web/public/wiki.css @@ -0,0 +1,198 @@ +/* Public documentation site — reuses the dashboard tokens from styles.css (M17). */ + +.wiki-body { + background: var(--bg); +} + +.wiki-shell { + display: grid; + grid-template-columns: 270px minmax(0, 1fr); + max-width: 1280px; + margin: 0 auto; + min-height: 100vh; +} + +.wiki-side { + border-right: 1px solid var(--border); + padding: 1.2rem 1rem; + display: flex; + flex-direction: column; + gap: 0.8rem; + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; +} + +.wiki-brand { + display: flex; + align-items: center; + gap: 0.6rem; + color: var(--text); +} +.wiki-brand:hover { + text-decoration: none; +} +.wiki-brand strong { + display: block; + font-size: 1rem; +} +.wiki-brand span { + display: block; + font-size: 0.75rem; + color: var(--text-muted); +} + +.wiki-nav, +.wiki-results { + display: flex; + flex-direction: column; + gap: 0.1rem; +} +.wiki-nav a, +.wiki-results a { + display: block; + padding: 0.38rem 0.6rem; + border-radius: var(--radius-sm); + color: var(--text); + font-size: 0.88rem; +} +.wiki-nav a:hover, +.wiki-results a:hover { + background: var(--surface); + text-decoration: none; +} +.wiki-nav a.active { + background: color-mix(in srgb, var(--blue) 16%, transparent); + color: var(--blue-soft); + font-weight: 600; + box-shadow: inset 3px 0 0 var(--blue); +} + +.wiki-main { + padding: 2rem 2.4rem 4rem; + min-width: 0; +} + +.wiki-article { + display: grid; + grid-template-columns: minmax(0, 1fr) 200px; + gap: 2rem; + align-items: start; +} + +.wiki-article h1 { + font-size: 2rem; + margin-bottom: 0.4rem; +} +.wiki-summary { + color: var(--text-muted); + font-size: 1.02rem; + margin-bottom: 1.4rem; +} + +/* Comfortable measure: long legal text is unreadable across a full screen. */ +.wiki-content { + max-width: 72ch; + font-size: 0.97rem; + line-height: 1.7; +} +.wiki-content h2 { + font-size: 1.32rem; + margin: 2rem 0 0.7rem; + padding-top: 0.6rem; + border-top: 1px solid var(--border); +} +.wiki-content h3 { + font-size: 1.08rem; + margin: 1.4rem 0 0.5rem; +} +.wiki-content h4 { + font-size: 0.97rem; + margin: 1.1rem 0 0.4rem; + color: var(--text-muted); +} +.wiki-content p { + margin: 0 0 0.9rem; +} +.wiki-content ul, +.wiki-content ol { + margin: 0 0 1rem; + padding-left: 1.35rem; +} +.wiki-content li { + margin-bottom: 0.35rem; +} +.wiki-content blockquote { + margin: 1rem 0; + padding: 0.7rem 1rem; + border-left: 3px solid var(--blue); + background: var(--surface); + border-radius: 0 var(--radius-sm) var(--radius-sm) 0; + color: var(--text-muted); +} +.wiki-content hr { + border: none; + border-top: 1px solid var(--border); + margin: 2rem 0; +} +.wiki-content img { + max-width: 100%; + border-radius: var(--radius-sm); +} +.wiki-content .table-wrap { + margin-bottom: 1.2rem; +} + +.wiki-toc { + position: sticky; + top: 2rem; + display: flex; + flex-direction: column; + gap: 0.1rem; + border-left: 1px solid var(--border); + padding-left: 0.9rem; +} +.wiki-toc a { + font-size: 0.8rem; + color: var(--text-muted); + padding: 0.18rem 0; +} +.wiki-toc a:hover { + color: var(--text); + text-decoration: none; +} +.wiki-toc a[data-level='3'] { + padding-left: 0.7rem; +} + +.wiki-updated { + margin-top: 2.5rem; + padding-top: 0.8rem; + border-top: 1px solid var(--border); + font-size: 0.8rem; +} + +@media (max-width: 1080px) { + .wiki-article { + grid-template-columns: minmax(0, 1fr); + } + .wiki-toc { + display: none; + } +} + +@media (max-width: 860px) { + .wiki-shell { + grid-template-columns: 1fr; + } + .wiki-side { + position: static; + height: auto; + border-right: none; + border-bottom: 1px solid var(--border); + } + .wiki-main { + padding: 1.2rem 1rem 3rem; + } +} diff --git a/src/web/public/wiki.html b/src/web/public/wiki.html new file mode 100644 index 0000000..90bc8e3 --- /dev/null +++ b/src/web/public/wiki.html @@ -0,0 +1,19 @@ + + + + + + + + Documentation FWS + + + + + +
    + +
    + + + diff --git a/src/web/public/wiki.js b/src/web/public/wiki.js new file mode 100644 index 0000000..88ae525 --- /dev/null +++ b/src/web/public/wiki.js @@ -0,0 +1,183 @@ +import { h, mount, qs } from './core/dom.js'; +import { render as renderMarkdown } from './core/markdown.js'; + +/** + * Public documentation site (M17). + * + * Standalone on purpose: no session, no dashboard shell, and its own small + * bundle — a visitor reading the privacy notice should never meet a login page. + */ + +const state = { tree: null, slug: null, theme: localStorage.getItem('fws.theme') ?? 'dark' }; + +const api = async (path) => { + const response = await fetch(path, { headers: { Accept: 'application/json' } }); + if (!response.ok) throw new Error((await response.json().catch(() => null))?.error ?? 'Page introuvable.'); + return response.json(); +}; + +const currentSlug = () => { + const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/\/$/, ''); + return decodeURIComponent(path) || null; +}; + +function navigate(slug, { replace = false } = {}) { + const url = slug ? `/wiki/${encodeURIComponent(slug)}` : '/wiki'; + if (replace) window.history.replaceState({}, '', url); + else window.history.pushState({}, '', url); + draw(); +} + +function sidebar() { + const search = h('input', { + class: 'input', + type: 'search', + placeholder: 'Rechercher…', + 'aria-label': 'Rechercher dans la documentation', + }); + const results = h('div', { class: 'wiki-results' }); + + let timer = null; + search.addEventListener('input', () => { + clearTimeout(timer); + const term = search.value.trim(); + if (term.length < 2) { + mount(results); + return; + } + timer = setTimeout(async () => { + const { results: found } = await api(`/api/wiki/search?q=${encodeURIComponent(term)}`).catch(() => ({ + results: [], + })); + mount( + results, + found.length === 0 + ? h('p', { class: 'muted', text: 'Aucun résultat.' }) + : found.map((page) => + h('a', { + href: `/wiki/${page.slug}`, + text: page.title, + onClick: (event) => { + event.preventDefault(); + search.value = ''; + mount(results); + navigate(page.slug); + }, + }), + ), + ); + }, 250); + }); + + return h( + 'aside', + { class: 'wiki-side' }, + h( + 'a', + { class: 'wiki-brand', href: '/wiki' }, + h('img', { src: '/favicon.svg', alt: '', width: 36, height: 36 }), + h('div', {}, h('strong', { text: 'FWS' }), h('span', { text: 'Documentation' })), + ), + search, + results, + h( + 'nav', + { class: 'wiki-nav' }, + (state.tree?.categories ?? []).map((category) => + h( + 'div', + {}, + h('div', { class: 'nav-group', text: category.name }), + category.pages.map((page) => + h('a', { + href: `/wiki/${page.slug}`, + text: page.title, + class: page.slug === state.slug ? 'active' : '', + onClick: (event) => { + event.preventDefault(); + navigate(page.slug); + }, + }), + ), + ), + ), + ), + ); +} + +function tableOfContents(headings) { + if (headings.length < 2) return null; + return h( + 'nav', + { class: 'wiki-toc' }, + h('div', { class: 'nav-group', text: 'Sur cette page' }), + headings.map((heading) => + h('a', { href: `#${heading.id}`, text: heading.text, dataset: { level: String(heading.level) } }), + ), + ); +} + +async function article(host) { + const slug = state.slug ?? state.tree?.categories?.[0]?.pages?.[0]?.slug ?? null; + if (!slug) { + mount(host, h('p', { class: 'empty', text: 'Aucune page publiée pour l’instant.' })); + return; + } + + let page; + try { + page = await api(`/api/wiki/pages/${encodeURIComponent(slug)}`); + } catch (error) { + mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message }))); + return; + } + + document.title = `${page.title} · Documentation FWS`; + const { html, headings } = renderMarkdown(page.content); + + const body = h('div', { class: 'wiki-content' }); + body.innerHTML = html; + + mount( + host, + h( + 'div', + { class: 'wiki-article' }, + h( + 'article', + {}, + h('p', { class: 'muted', text: page.category }), + h('h1', { text: page.title }), + page.summary && h('p', { class: 'wiki-summary', text: page.summary }), + body, + h('footer', { + class: 'muted wiki-updated', + text: `Dernière modification : ${new Date(`${page.updatedAt}Z`).toLocaleDateString('fr-FR', { + dateStyle: 'long', + })}`, + }), + ), + tableOfContents(headings), + ), + ); +} + +async function draw() { + state.slug = currentSlug(); + const root = qs('#wiki'); + + if (!state.tree) { + state.tree = await api('/api/wiki').catch(() => ({ categories: [], site: {} })); + } + + const main = h('main', { class: 'wiki-main' }); + mount(root, h('div', { class: 'wiki-shell' }, sidebar(), main)); + await article(main); + + // In-page anchors only work once the article is on screen. + if (window.location.hash) qs(window.location.hash)?.scrollIntoView({ block: 'start' }); +} + +document.documentElement.dataset.theme = state.theme; +window.addEventListener('popstate', draw); +draw(); diff --git a/tests/web-wiki.test.js b/tests/web-wiki.test.js new file mode 100644 index 0000000..25f994b --- /dev/null +++ b/tests/web-wiki.test.js @@ -0,0 +1,215 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + createPage, + getPageBySlug, + listPublished, + removePage, + searchPublished, + updatePage, +} from '../src/database/repositories/wiki-repository.js'; +import { render } from '../src/web/public/core/markdown.js'; +import { createHandler } from '../src/web/server.js'; +import { seedWiki } from '../src/web/services/wiki-seed.js'; + +/** Public wiki and its Markdown renderer (M17). */ + +describe('markdown renderer', () => { + it('escapes HTML before doing anything else', () => { + const { html } = render(''); + assert.doesNotMatch(html, / - - diff --git a/src/web/public/wiki.js b/src/web/public/wiki.js deleted file mode 100644 index 242e297..0000000 --- a/src/web/public/wiki.js +++ /dev/null @@ -1,187 +0,0 @@ -import { h, mount, qs } from './core/dom.js'; -import { render as renderMarkdown } from './core/markdown.js'; - -/** - * Public documentation site (M17). - * - * Standalone on purpose: no session, no dashboard shell, and its own small - * bundle — a visitor reading the privacy notice should never meet a login page. - */ - -const state = { tree: null, slug: null, theme: localStorage.getItem('fws.theme') ?? 'dark' }; - -const api = async (path) => { - const response = await fetch(path, { headers: { Accept: 'application/json' } }); - if (!response.ok) throw new Error((await response.json().catch(() => null))?.error ?? 'Page introuvable.'); - return response.json(); -}; - -const currentSlug = () => { - // A page answers either at `/wiki/` or, for the legal ones, at - // `/`; the last segment is the slug in both cases. - const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/^\/|\/$/g, ''); - return decodeURIComponent(path) || null; -}; - -const pathOf = (page) => page?.path ?? (page?.slug ? `/wiki/${encodeURIComponent(page.slug)}` : '/wiki'); - -function navigate(target, { replace = false } = {}) { - const url = typeof target === 'string' ? target : pathOf(target); - if (replace) window.history.replaceState({}, '', url); - else window.history.pushState({}, '', url); - draw(); -} - -function sidebar() { - const search = h('input', { - class: 'input', - type: 'search', - placeholder: 'Rechercher…', - 'aria-label': 'Rechercher dans la documentation', - }); - const results = h('div', { class: 'wiki-results' }); - - let timer = null; - search.addEventListener('input', () => { - clearTimeout(timer); - const term = search.value.trim(); - if (term.length < 2) { - mount(results); - return; - } - timer = setTimeout(async () => { - const { results: found } = await api(`/api/wiki/search?q=${encodeURIComponent(term)}`).catch(() => ({ - results: [], - })); - mount( - results, - found.length === 0 - ? h('p', { class: 'muted', text: 'Aucun résultat.' }) - : found.map((page) => - h('a', { - href: pathOf(page), - text: page.title, - onClick: (event) => { - event.preventDefault(); - search.value = ''; - mount(results); - navigate(page); - }, - }), - ), - ); - }, 250); - }); - - return h( - 'aside', - { class: 'wiki-side' }, - h( - 'a', - { class: 'wiki-brand', href: '/wiki' }, - h('img', { src: '/favicon.svg', alt: '', width: 36, height: 36 }), - h('div', {}, h('strong', { text: 'FWS' }), h('span', { text: 'Documentation' })), - ), - search, - results, - h( - 'nav', - { class: 'wiki-nav' }, - (state.tree?.categories ?? []).map((category) => - h( - 'div', - {}, - h('div', { class: 'nav-group', text: category.name }), - category.pages.map((page) => - h('a', { - href: pathOf(page), - text: page.title, - class: page.slug === state.slug ? 'active' : '', - onClick: (event) => { - event.preventDefault(); - navigate(page); - }, - }), - ), - ), - ), - ), - ); -} - -function tableOfContents(headings) { - if (headings.length < 2) return null; - return h( - 'nav', - { class: 'wiki-toc' }, - h('div', { class: 'nav-group', text: 'Sur cette page' }), - headings.map((heading) => - h('a', { href: `#${heading.id}`, text: heading.text, dataset: { level: String(heading.level) } }), - ), - ); -} - -async function article(host) { - const slug = state.slug ?? state.tree?.categories?.[0]?.pages?.[0]?.slug ?? null; - if (!slug) { - mount(host, h('p', { class: 'empty', text: 'Aucune page publiée pour l’instant.' })); - return; - } - - let page; - try { - page = await api(`/api/wiki/pages/${encodeURIComponent(slug)}`); - } catch (error) { - mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message }))); - return; - } - - document.title = `${page.title} · Documentation FWS`; - const { html, headings } = renderMarkdown(page.content); - - const body = h('div', { class: 'wiki-content' }); - body.innerHTML = html; - - mount( - host, - h( - 'div', - { class: 'wiki-article' }, - h( - 'article', - {}, - h('p', { class: 'muted', text: page.category }), - h('h1', { text: page.title }), - page.summary && h('p', { class: 'wiki-summary', text: page.summary }), - body, - h('footer', { - class: 'muted wiki-updated', - text: `Dernière modification : ${new Date(`${page.updatedAt}Z`).toLocaleDateString('fr-FR', { - dateStyle: 'long', - })}`, - }), - ), - tableOfContents(headings), - ), - ); -} - -async function draw() { - state.slug = currentSlug(); - const root = qs('#wiki'); - - if (!state.tree) { - state.tree = await api('/api/wiki').catch(() => ({ categories: [], site: {} })); - } - - const main = h('main', { class: 'wiki-main' }); - mount(root, h('div', { class: 'wiki-shell' }, sidebar(), main)); - await article(main); - - // In-page anchors only work once the article is on screen. - if (window.location.hash) qs(window.location.hash)?.scrollIntoView({ block: 'start' }); -} - -document.documentElement.dataset.theme = state.theme; -window.addEventListener('popstate', draw); -draw(); diff --git a/src/web/server.js b/src/web/server.js index f56c0c9..46f1f5d 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -9,13 +9,71 @@ import { registerApiRoutes } from './api/index.js'; import { authenticate, assertSameOrigin } from './auth/session.js'; import { authorize } from './auth/guard.js'; import { broadcast, closeEventStreams, topicForPath } from './events.js'; -import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; +import { HttpError, readJsonBody, readRawBody, sendEmpty, sendHtml, sendJson, sendStatic } from './http.js'; import { createRouter } from './router.js'; +import { listPublished } from '../database/repositories/wiki-repository.js'; +import { pagePath } from './services/wiki-seed.js'; +import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js'; import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js'; /** HTTP server of the dashboard (M16-T01). */ const log = createLogger('web'); + +/** + * The wiki address a path stands for: `''` for the index, a slug for a page, + * `null` when the path is not the wiki's business. + */ +function wikiSlug(pathname) { + const clean = pathname.replace(/\/+$/, ''); + if (clean === '/wiki' || clean === '') return clean === '/wiki' ? '' : null; + if (clean.startsWith('/wiki/')) return decodeURIComponent(clean.slice('/wiki/'.length)); + + const root = clean.replace(/^\//, ''); + return ROOT_PAGES.includes(root) ? root : null; +} + +/** Answers with the finished HTML of a wiki page, or its index. */ +function sendWiki(response, slug, term) { + let pages = []; + try { + pages = listPublished(); + } catch (error) { + log.warn('Could not read the wiki pages', error); + } + + const categories = []; + for (const page of pages) { + const entry = { ...page, path: pagePath(page.slug) }; + let category = categories.find((item) => item.name === page.category); + if (!category) categories.push((category = { name: page.category, pages: [] })); + category.pages.push(entry); + } + const all = categories.flatMap((category) => category.pages); + + if (slug === '') { + const needle = term.trim().toLowerCase(); + const results = + needle.length >= 2 + ? all.filter((page) => + [page.title, page.summary, page.content].some((field) => + String(field ?? '') + .toLowerCase() + .includes(needle), + ), + ) + : null; + sendHtml(response, 200, renderIndex(categories, { term, results })); + return; + } + + const page = all.find((entry) => entry.slug === slug); + if (!page) { + sendHtml(response, 404, renderNotFound(categories)); + return; + } + sendHtml(response, 200, renderPage(page, categories)); +} const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public'); /** Sliding window per client address, reset every minute. */ @@ -72,15 +130,20 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/'); if (!isApi) { - // The wiki is a separate public page: it must never fall back to the - // dashboard shell, which would send a visitor to a login screen. The - // legal pages answer at the root, where platforms expect them. - const isWiki = - pathname === '/wiki' || - pathname.startsWith('/wiki/') || - ROOT_PAGES.includes(pathname.replace(/^\/|\/$/g, '')); - const fallback = isWiki ? 'wiki.html' : 'index.html'; - const served = await sendStatic(response, publicDir, pathname, { fallback, request }); + // The wiki is rendered here rather than in the browser: a terms page + // that needs scripts to show its text reads as blank to anything that + // does not run them, which includes whoever checks the link before + // approving an application. + const slug = wikiSlug(pathname); + if (slug !== null) { + sendWiki(response, slug, url.searchParams.get('q') ?? ''); + return; + } + + const served = await sendStatic(response, publicDir, pathname, { + fallback: 'index.html', + request, + }); if (!served) sendEmpty(response, 404); return; } diff --git a/src/web/services/wiki-render.js b/src/web/services/wiki-render.js new file mode 100644 index 0000000..5aee81e --- /dev/null +++ b/src/web/services/wiki-render.js @@ -0,0 +1,182 @@ +import { env } from '../../config/env.js'; +import { render as renderMarkdown } from '../public/core/markdown.js'; +import { pagePath } from './wiki-seed.js'; + +/** + * Server-rendered wiki (M17). + * + * The public documentation is delivered as finished HTML rather than assembled + * in the browser. A terms page that needs JavaScript to show its text is a page + * that reads as blank to anything that does not run scripts — a platform + * checking the link before approving an application, a crawler, a reader with + * scripts disabled — and those are exactly the readers it exists for. + */ + +const escape = (text) => + String(text ?? '') + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +const document = ({ title, description, body, noindex = false }) => ` + + + + + + + + ${escape(title)} + + + + + +${body} + + +`; + +/** Sidebar: the page tree and a search box that works without scripts. */ +function sidebar(categories, currentSlug, term = '') { + const groups = categories + .map( + (category) => ` + + ${category.pages + .map( + (page) => + `${escape(page.title)}`, + ) + .join('\n ')}`, + ) + .join('\n'); + + return ` `; +} + +/** Table of contents, built from the headings the renderer collected. */ +const contents = (headings) => + headings.length < 2 + ? '' + : ` `; + +const footerLinks = () => { + const links = [ + env.links.website && `Site`, + env.links.docs && `Documentation`, + `Conditions d'utilisation`, + `Politique de confidentialité`, + ].filter(Boolean); + return `
    ${links.join(' · ')}
    `; +}; + +const shell = (categories, currentSlug, main, term) => `
    +${sidebar(categories, currentSlug, term)} +
    +${main} +${footerLinks()} +
    +
    `; + +/** A page, with its body already turned into HTML. */ +export function renderPage(page, categories) { + const { html, headings } = renderMarkdown(page.content); + const updated = new Date(`${page.updated_at}Z`); + + const main = `
    +
    +

    ${escape(page.category)}

    +

    ${escape(page.title)}

    + ${page.summary ? `

    ${escape(page.summary)}

    ` : ''} +
    +${html} +
    +
    + Dernière modification : + +
    +
    +${contents(headings)} +
    `; + + return document({ + title: `${page.title} · Documentation FWS`, + description: page.summary || `${page.title} — documentation de l'organisation FWS.`, + body: shell(categories, page.slug, main), + }); +} + +/** Landing page, and the search results when a term is given. */ +export function renderIndex(categories, { term = '', results = null } = {}) { + const list = (pages) => + pages.length === 0 + ? '

    Aucun résultat.

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

    Recherche

    +

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

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

    Documentation FWS

    +

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

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

    ${escape(category.name)}

    ${list(category.pages)}`) + .join('\n ')} +
    `; + + return document({ + title: 'Documentation FWS', + description: "Documentation publique de l'organisation open source FWS.", + body: shell(categories, null, main, term), + }); +} + +export function renderNotFound(categories) { + const main = ` `; + + return document({ + title: 'Page introuvable · Documentation FWS', + description: 'Page introuvable.', + body: shell(categories, null, main), + noindex: true, + }); +} diff --git a/tests/web-wiki.test.js b/tests/web-wiki.test.js index bede6b8..c55aa26 100644 --- a/tests/web-wiki.test.js +++ b/tests/web-wiki.test.js @@ -207,10 +207,48 @@ describe('wiki over HTTP', () => { for (const path of ['/terms-of-service', '/privacy-policy']) { const response = await get(path); assert.equal(response.status, 200, `${path} ne répond pas`); - assert.match(await response.text(), /wiki\.js/, `${path} ne sert pas le site public`); + assert.match(response.headers.get('content-type'), /text\/html/); } }); + /** + * The point of the whole exercise: whoever checks these links before + * approving an application does not run scripts. + */ + it('delivers the legal text without any script', async () => { + const terms = await get('/terms-of-service').then((response) => response.text()); + const privacy = await get('/privacy-policy').then((response) => response.text()); + + assert.match(terms, /droit suisse/, 'les conditions ne sont pas dans le HTML'); + assert.match(privacy, /LPD/, 'la politique n’est pas dans le HTML'); + assert.match(privacy, /PFPDT/); + assert.doesNotMatch(terms, /