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; }