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:
11 files changed
+2713
No files matched your search
@@ -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 },
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user