// SPDX-License-Identifier: GPL-3.0-only // Copyright (C) 2026 poli0981 (SkullMute) // // docs/12 §4 — the bots' side of the forge (D38): pull requests, issues, // workflow dispatches and commit statuses through Gitea's REST API. // // The `gh` CLI and peter-evans/create-pull-request went with the GitHub // account. The workflows that talk back to the forge (quarantine, vt-recheck, // link-check, ci's `record` job) call this script with the job token; it needs // nothing but Node's fetch. // // GITEA_API ${{ github.api_url }} https://git.poli0981.dev/api/v1 // GITEA_REPO ${{ github.repository }} poli0981/softharbor // GITEA_TOKEN ${{ github.token }} // // pr <body-file> [labels] open, or update, the PR <head> → main // pr-open <head> is a PR from <head> open? (open=true|false) // dispatch <ref> <workflow.yml>... run those workflows on <ref> // status <sha> <context> <result> [url] record a job's result as a commit status // quarantine-issues <slug>... one tracking issue per newly quarantined slug // vt-issues <review.json> one tracking issue per entry with detections // link-rot <exit-code> <report> <run-url> refresh, open or close the link-check issue // // Two Gitea facts shape it (runbook §6): an event the job token causes starts // no workflow — so a bot PR gets its checks from `dispatch` — and a dispatched // run writes no commit status — so ci.yml records its own (`status`), under the // names branch protection matches. import { appendFileSync, readFileSync } from 'node:fs'; const BASE = 'main'; const PAGE = 50; // Gitea's default MAX_RESPONSE_ITEMS const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/; export const LINK_ROT_TITLE = 'link-check: broken official links'; /** A Gitea API caller for one repository: `call(method, path, body?)` → parsed JSON. */ export function client({ api, repo, token }) { return async function call(method, path, body) { const res = await fetch(`${api}/repos/${repo}${path}`, { method, headers: { authorization: `token ${token}`, accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }), }, body: body === undefined ? undefined : JSON.stringify(body), }); const text = await res.text(); if (!res.ok) throw new Error(`${method} ${path} → ${res.status} ${text.slice(0, 300)}`); return text ? JSON.parse(text) : null; }; } /** Every row of a paged list endpoint. */ async function all(call, path) { const rows = []; for (let page = 1; ; page++) { const sep = path.includes('?') ? '&' : '?'; const batch = await call('GET', `${path}${sep}limit=${PAGE}&page=${page}`); rows.push(...batch); if (batch.length < PAGE) return rows; } } /** * Label names → ids. Gitea attaches labels by id, and its API creates none: * a missing label is left off with a notice instead of failing the bot. */ async function labelIds(call, names, log) { if (names.length === 0) return []; const byName = new Map((await all(call, '/labels')).map((l) => [l.name, l.id])); const ids = []; for (const name of names) { if (byName.has(name)) ids.push(byName.get(name)); else log(`::notice::label "${name}" does not exist on this repository — left off`); } return ids; } export async function findPull(call, head) { const pulls = await all(call, '/pulls?state=open'); return pulls.find((p) => p.head?.ref === head && p.base?.ref === BASE) ?? null; } export async function openPull(call, { head, title, body, labels = [], log = console.log }) { const existing = await findPull(call, head); if (existing) { await call('PATCH', `/pulls/${existing.number}`, { title, body }); log(`Updated pull request #${existing.number}`); return { number: existing.number, operation: 'updated' }; } const pull = await call('POST', '/pulls', { base: BASE, head, title, body, labels: await labelIds(call, labels, log), }); log(`Opened pull request #${pull.number}`); return { number: pull.number, operation: 'created' }; } async function findIssue(call, title) { const issues = await all(call, '/issues?state=open&type=issues'); return issues.find((i) => i.title === title) ?? null; } /** Opens an issue unless one with the same title is already open. */ export async function openIssue(call, { title, body, labels = [], log = console.log }) { const existing = await findIssue(call, title); if (existing) { log(`${title} is already tracked in #${existing.number}`); return null; } const issue = await call('POST', '/issues', { title, body, labels: await labelIds(call, labels, log), }); log(`Opened #${issue.number}: ${title}`); return issue.number; } export async function dispatch(call, ref, workflows, log = console.log) { for (const file of workflows) { await call('POST', `/actions/workflows/${encodeURIComponent(file)}/dispatches`, { ref }); log(`Dispatched ${file} on ${ref}`); } } /** A `needs.<job>.result` as a commit status. Cancelled and skipped jobs record nothing. */ export async function recordStatus(call, { sha, context, result, url, log = console.log }) { if (result !== 'success' && result !== 'failure') { log(`${context}: ${result || 'no result'} — nothing to record`); return false; } await call('POST', `/statuses/${sha}`, { state: result, context, description: result === 'success' ? 'passed in this dispatched run' : 'failed in this dispatched run — see the run', ...(url ? { target_url: url } : {}), }); log(`${context}: recorded ${result} on ${sha}`); return true; } export function quarantineBody(slug) { return `\`${slug}\` was flagged and moved to \`data/quarantine/\`. Record here before closing: - [ ] Reason it was flagged - [ ] Evidence link (VirusTotal / vendor advisory) - [ ] Date checked - [ ] Whether users were plausibly exposed (docs/13 §7) Restoring is a reviewed PR: status back to \`clean\`/\`unverified\`, a fresh \`checkedAt\`, and the file moved back (docs/03 §5). `; } export function vtBody({ slug, evidence, malicious, suspicious, was, status }) { return `VirusTotal re-scanned \`${slug}\`'s download page: **${malicious} malicious, ${suspicious} suspicious** — [the scan](${evidence}). Status in the re-check PR: \`${was}\` → \`${status}\`. Nothing was flagged or removed (docs/09 §6). Decide and record here: - [ ] Look at which engines said what, and whether the vendor or a second scan agrees - [ ] False positive → set \`status\` back to \`clean\` in a PR and note why here - [ ] Confirmed → \`status: "flagged"\` + \`pnpm quarantine\` in one PR (docs/03 §5) - [ ] Whether users were plausibly exposed (docs/13 §7) `; } /** Slugs come from our own scripts; anything else must not reach an issue title. */ function validSlugs(slugs, log) { return slugs.filter((slug) => { if (SLUG.test(slug)) return true; log(`::warning::skipping unexpected slug '${slug}'`); return false; }); } export async function quarantineIssues(call, slugs, log = console.log) { for (const slug of validSlugs(slugs, log)) { await openIssue(call, { title: `[quarantine] ${slug}`, body: quarantineBody(slug), labels: ['security', 'quarantine'], log, }); } } export async function vtIssues(call, rows, log = console.log) { const bySlug = new Map(rows.map((r) => [r.slug, r])); for (const slug of validSlugs([...bySlug.keys()], log)) { await openIssue(call, { title: `[vt] ${slug}`, body: vtBody(bySlug.get(slug)), labels: ['security'], log, }); } } /** * ONE tracking issue for the weekly link sweep: refreshed in place while the * sweep fails, closed the first week it comes back clean (docs/12 §5). */ export async function linkRot(call, { failing, report, runUrl, log = console.log }) { const existing = await findIssue(call, LINK_ROT_TITLE); if (failing && existing) { await call('PATCH', `/issues/${existing.number}`, { body: report }); await call('POST', `/issues/${existing.number}/comments`, { body: `Still failing in ${runUrl} — the report above was refreshed.`, }); log(`Refreshed #${existing.number}`); return 'refreshed'; } if (failing) { await openIssue(call, { title: LINK_ROT_TITLE, body: report, labels: ['link-rot'], log }); return 'opened'; } if (existing) { await call('POST', `/issues/${existing.number}/comments`, { body: `Every official link resolved in ${runUrl}. Closing; the next failure opens a fresh report.`, }); await call('PATCH', `/issues/${existing.number}`, { state: 'closed' }); log(`Closed #${existing.number}`); return 'closed'; } log('All links healthy; nothing to report.'); return 'healthy'; } const USAGE = 'usage: gitea.mjs <pr|pr-open|dispatch|status|quarantine-issues|vt-issues|link-rot> …'; /** How many arguments each command needs at least. */ const ARITY = { pr: 3, 'pr-open': 1, dispatch: 2, status: 3, 'quarantine-issues': 0, 'vt-issues': 1, 'link-rot': 3, }; function fail(message) { console.error(`::error::gitea.mjs: ${message}`); return 1; } /** Runs one command; its input is already checked. */ async function run(call, command, args, out) { switch (command) { case 'pr': { const [head, title, bodyFile, labels = ''] = args; const r = await openPull(call, { head, title, body: readFileSync(bodyFile, 'utf8'), labels: labels .split(',') .map((s) => s.trim()) .filter(Boolean), }); out('number', r.number); out('operation', r.operation); return; } case 'pr-open': { const pull = await findPull(call, args[0]); console.log(pull ? `#${pull.number} is open` : `No open pull request from ${args[0]}`); out('open', pull ? 'true' : 'false'); return; } case 'dispatch': await dispatch(call, args[0], args.slice(1)); return; case 'status': { const [sha, context, result, url] = args; await recordStatus(call, { sha, context, result, url }); return; } case 'quarantine-issues': await quarantineIssues(call, args); return; case 'vt-issues': await vtIssues(call, JSON.parse(readFileSync(args[0], 'utf8'))); return; default: { // 'link-rot' — the last command ARITY knows. const [exitCode, reportFile, runUrl] = args; await linkRot(call, { failing: exitCode !== '0', report: readFileSync(reportFile, 'utf8'), runUrl, }); } } } export async function main(argv = process.argv.slice(2), env = process.env) { const out = (key, value) => { if (env['GITHUB_OUTPUT']) appendFileSync(env['GITHUB_OUTPUT'], `${key}=${value}\n`); }; const [command = '', ...args] = argv; const { GITEA_API: api, GITEA_REPO: repo, GITEA_TOKEN: token } = env; if (!api || !repo || !token) return fail('GITEA_API, GITEA_REPO and GITEA_TOKEN are required'); if (!Object.hasOwn(ARITY, command)) return fail(USAGE); if (args.length < ARITY[command]) return fail(`${command} needs ${ARITY[command]} argument(s) — ${USAGE}`); try { await run(client({ api, repo, token }), command, args, out); return 0; } catch (e) { return fail(e.message); } } if (import.meta.main) process.exitCode = await main();