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) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 20:09:13 +02:00
1 parent 611129b23c
commit bf92badb05
11 files changed
+2713

No files matched your search

+260
View File
@@ -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 = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/;
/**
* 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(),
},
],
});
}