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