Releases from git tags and WHATS-NEW.md; docs, changelog (1.4.0)

The Hub reads the Cross Events repo's v* tags (each a release, the newest the
latest version) and the client notes from WHATS-NEW.md as of the newest tag,
every 15 minutes and on Sync now. Urgent/security in a version heading marks it
urgent. Repo address, notes path and an optional encrypted token on the
Releases page; manual releases only when no repo is set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 09:13:30 +02:00
co-authored by Claude Opus 5.5
parent 1449e5046e
commit 0adb304024
13 changed files with 380 additions and 38 deletions
+4 -1
View File
@@ -11,6 +11,7 @@ const app = require('./app');
const { keyPair } = require('./utils/licenceToken');
const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
const { importSmtpFromEnv } = require('./utils/settings');
const { syncReleases } = require('./utils/releaseSync');
// Fail early if the licence signing key is missing or wrong.
try {
@@ -28,11 +29,13 @@ importSmtpFromEnv()
const PORT = parseInt(process.env.PORT || '5200', 10);
app.listen(PORT, () => console.log(`[hub] Listening on ${PORT}`));
// Background checks: alerts every 5 minutes, heartbeat roll-up once a day. The Hub runs as a
// Background checks: alerts every 5 minutes, releases from git every 15, heartbeat roll-up once a day. The Hub runs as a
// single process, so plain timers are enough.
if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() !== 'false') {
const every = (ms, name, fn) => setInterval(() => fn().catch(e => console.warn(`[hub] ${name} failed:`, e?.message || e)), ms);
every(5 * 60 * 1000, 'alerts', () => runAlerts());
every(15 * 60 * 1000, 'release sync', () => syncReleases());
every(24 * 60 * 60 * 1000, 'heartbeat roll-up', () => rollupHeartbeats());
setTimeout(() => runAlerts().catch(() => {}), 30 * 1000);
setTimeout(() => syncReleases().catch(e => console.warn('[hub] release sync failed:', e?.message || e)), 20 * 1000);
}
+30 -5
View File
@@ -12,6 +12,7 @@ const licenceToken = require('../utils/licenceToken');
const { smtpConfigured, testSmtp } = require('../utils/mail');
const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releases');
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases } = require('../utils/releaseSync');
const router = express.Router();
router.use(protect);
@@ -21,7 +22,7 @@ const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardH
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[admin]', e);
res.status(status).json({ message: status >= 500 ? 'Something went wrong.' : e.message });
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message });
});
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
@@ -228,7 +229,8 @@ router.get('/audit', wrap(async (req, res) => {
// ─── Releases ─────────────────────────────────────────────────────────────────
// What's new in each Cross Events version. Installs on an older version see the notes; the highest
// version is the latest (latest_version), so adding one tells installs an update is out.
// version is the latest (latest_version), so adding one tells installs an update is out. With a git
// repository set (Releases page), releases come from its tags and WHATS-NEW.md only.
router.get('/releases', wrap(async (req, res) => {
const [releases, installs] = await Promise.all([
@@ -253,6 +255,22 @@ function releaseData(body, { partial = false } = {}) {
return data;
}
async function manualReleases() {
if (parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Releases come from git: tag the version and edit WHATS-NEW.md, then Sync now.');
}
router.post('/releases/sync', wrap(async (req, res) => {
if (!parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Set the git repository first.');
let result;
try {
result = await syncReleases();
} catch (e) {
throw bad(e.message, 502);
}
await audit(req, 'releases_synced', null, result);
res.json(result);
}));
const releaseError = e => {
if (e.code === 'P2002') throw bad('There is already a release with that version.', 409);
if (e.code === 'P2025') throw bad('Release not found', 404);
@@ -260,6 +278,7 @@ const releaseError = e => {
};
router.post('/releases', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_added', release.id, { version: release.version, urgent: release.urgent });
@@ -267,6 +286,7 @@ router.post('/releases', wrap(async (req, res) => {
}));
router.put('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const data = releaseData(req.body, { partial: true });
const release = await prisma.release.update({ where: { id: req.params.id }, data }).catch(releaseError);
const latest = await syncLatestVersion();
@@ -275,6 +295,7 @@ router.put('/releases/:id', wrap(async (req, res) => {
}));
router.delete('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_deleted', release.id, { version: release.version });
@@ -365,16 +386,20 @@ function checkSmtp(values) {
// What the audit log records: never the password, only that it changed.
function auditValues(values) {
const { smtp_pass, smtp_pass_clear, ...rest } = values;
const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_clear, ...rest } = values;
if (smtp_pass_clear) rest.smtp_pass = '(removed)';
else if (smtp_pass) rest.smtp_pass = '(changed)';
if (release_repo_token_clear) rest.release_repo_token = '(removed)';
else if (release_repo_token) rest.release_repo_token = '(changed)';
return rest;
}
router.put('/settings', wrap(async (req, res) => {
// The latest version follows the Releases page.
// The latest version follows the Releases page; the sync writes its own status.
// eslint-disable-next-line no-unused-vars
const { latest_version, ...values } = req.body?.settings || {};
const { latest_version, release_synced_at, release_sync_error, ...values } = req.body?.settings || {};
if (values.release_repo_url && !parseRepoUrl(values.release_repo_url)) throw bad('The repository address looks like https://git.example.com/owner/repo.');
if (values.release_notes_path != null && !String(values.release_notes_path).trim()) values.release_notes_path = 'WHATS-NEW.md';
checkSmtp(values);
const settings = await setSettings(values);
await audit(req, 'settings_updated', null, auditValues(values));
+149
View File
@@ -0,0 +1,149 @@
/**
* Releases from git (Gitea): every v1.2.3 tag of the Cross Events repo is a release, dated by its
* commit, and the notes come from the repo's WHATS-NEW.md as of the newest tag ("## 1.2.3" sections;
* "urgent" or "security" in the heading marks an urgent release). Runs every 15 minutes and from
* "Sync now" on the Releases page, when a repo is set; git is then the only source of releases.
*/
const prisma = require('../config/db');
const { compareVersions } = require('./alerts');
const { getSettings, setSettings, releaseRepoToken } = require('./settings');
const { syncLatestVersion } = require('./releases');
const TIMEOUT_MS = 20000;
const TAG_RE = /^v?(\d+\.\d+\.\d+)$/;
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
function parseRepoUrl(url) {
try {
const u = new URL(String(url || '').trim());
if (!/^https?:$/.test(u.protocol)) return null;
const [owner, repo] = u.pathname.replace(/\/+$/, '').replace(/\.git$/, '').split('/').filter(Boolean);
if (!owner || !repo) return null;
return { api: `${u.origin}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, owner, repo };
} catch {
return null;
}
}
/** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */
function plainNotes(lines) {
const out = [];
for (const raw of lines) {
let line = raw.replace(/\s+$/, '');
if (!line.trim()) { out.push(''); continue; }
const indent = /^\s{2,}[-*]\s/.test(line);
line = line.trim()
.replace(/^#{1,6}\s+/, '')
.replace(/^[*+]\s+/, '- ')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/__(.+?)__/g, '$1')
.replace(/`([^`]+)`/g, '$1')
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
// A wrapped line continues the line above: an indented one after a list item, any one in a paragraph.
const prev = out[out.length - 1];
const continues = prev && !line.startsWith('- ') && !indent && (prev.startsWith('- ') ? /^\s/.test(raw) : true);
if (continues) out[out.length - 1] = `${prev} ${line}`;
else out.push(line);
}
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
/**
* The sections of WHATS-NEW.md: { "1.46.2": { notes, urgent } }. A section is a "## 1.46.2" heading
* (optionally "[1.46.2]", "v1.46.2", a date or "— urgent" after it) up to the next "## ".
*/
function parseNotes(markdown) {
const text = String(markdown || '').replace(/<!--[\s\S]*?-->/g, '');
const sections = {};
let current = null;
for (const line of text.split(/\r?\n/)) {
const heading = /^##\s+(.*)$/.exec(line);
if (heading) {
const v = /\[?v?(\d+\.\d+\.\d+)\]?/.exec(heading[1]);
current = v ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), lines: [] } : null;
if (current) sections[current.version] = current;
continue;
}
if (/^#\s/.test(line)) { current = null; continue; }
if (current) current.lines.push(line);
}
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent }]));
}
async function get(url, token, { raw = false } = {}) {
let res;
try {
res = await fetch(url, { headers: token ? { Authorization: `token ${token}` } : {}, signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (e) {
throw new Error(`Git could not be reached: ${e?.message || e}`);
}
if (res.status === 404) return null;
if (res.status === 401 || res.status === 403) throw new Error('Git refused access — check the access token (or that the repository is public).');
if (!res.ok) throw new Error(`Git answered ${res.status} for ${url}`);
return raw ? res.text() : res.json();
}
/** Every v1.2.3 tag: [{ version, date }]. */
async function fetchTags(repo, token) {
const tags = [];
for (let page = 1; page <= 20; page++) {
const batch = await get(`${repo.api}/tags?limit=50&page=${page}`, token);
if (batch === null) throw new Error('The repository was not found. Check its address (and the token if it is private).');
for (const t of batch) {
const m = TAG_RE.exec(t.name || '');
if (m) tags.push({ version: m[1], date: t.commit?.created || null });
}
if (batch.length < 50) break;
}
return tags;
}
/**
* Bring the releases in line with git: add new tags, update notes and urgency from WHATS-NEW.md, and
* remove releases that have no tag. Returns { tags, added, updated, removed, latest }.
*/
async function syncReleases() {
const settings = await getSettings();
const repo = parseRepoUrl(settings.release_repo_url);
if (!repo) return { skipped: 'no repository set' };
try {
const token = await releaseRepoToken();
const tags = await fetchTags(repo, token);
if (!tags.length) throw new Error('The repository has no version tags (v1.2.3) yet.');
const newest = tags.reduce((a, b) => (compareVersions(b.version, a.version) > 0 ? b : a));
const path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');
const markdown = await get(`${repo.api}/raw/${path}?ref=v${newest.version}`, token, { raw: true });
const notes = parseNotes(markdown || '');
const existing = new Map((await prisma.release.findMany()).map(r => [r.version, r]));
const tagged = new Set(tags.map(t => t.version));
let added = 0;
let updated = 0;
for (const tag of tags) {
const n = notes[tag.version] || { notes: '', urgent: false };
const had = existing.get(tag.version);
if (!had) {
await prisma.release.create({ data: { version: tag.version, notes: n.notes, urgent: n.urgent, releasedAt: tag.date ? new Date(tag.date) : new Date() } });
added++;
} else {
// Releases added by hand (or from the old latest_version setting) take the tag's date.
const date = tag.date ? new Date(tag.date) : had.releasedAt;
if (had.notes !== n.notes || had.urgent !== n.urgent || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: n.notes, urgent: n.urgent, releasedAt: date } });
updated++;
}
}
}
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
if (gone.length) await prisma.release.deleteMany({ where: { id: { in: gone } } });
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: markdown === null ? `${settings.release_notes_path} was not found at v${newest.version}, so there are no notes.` : '' });
return { tags: tags.length, added, updated, removed: gone.length, latest };
} catch (e) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${e.message}`.slice(0, 500) });
throw e;
}
}
module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases };
+31 -9
View File
@@ -17,29 +17,45 @@ const DEFAULTS = {
smtp_user: '',
smtp_pass: '',
smtp_from: '',
// Releases and their notes are read from git (utils/releaseSync.js) when a repo is set.
release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events',
release_notes_path: 'WHATS-NEW.md',
release_repo_token: '',
// Written by the sync, not the Settings page.
release_synced_at: '',
release_sync_error: '',
};
// Stored encrypted and never sent to the browser: only "is one saved" (<key>_set).
const SECRETS = ['smtp_pass', 'release_repo_token'];
async function rawSettings() {
const rows = await prisma.setting.findMany();
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
return { ...DEFAULTS, ...saved };
}
/** Settings for the Settings page: the SMTP password only as "is one saved". */
/** Settings for the Settings page: secrets (SMTP password, repo token) only as "is one saved". */
async function getSettings() {
const { smtp_pass, ...settings } = await rawSettings();
return { ...settings, smtp_pass_set: smtp_pass ? 'true' : '' };
const settings = await rawSettings();
for (const key of SECRETS) {
settings[`${key}_set`] = settings[key] ? 'true' : '';
delete settings[key];
}
return settings;
}
/**
* Save settings. A blank smtp_pass keeps the saved password (the page never has it);
* smtp_pass_clear removes it.
* Save settings. A blank secret keeps the saved one (the page never has it); <key>_clear
* removes it.
*/
async function setSettings(values) {
const input = { ...(values || {}) };
if (input.smtp_pass_clear) input.smtp_pass = '';
else if (input.smtp_pass) input.smtp_pass = encrypt(input.smtp_pass);
else delete input.smtp_pass;
for (const key of SECRETS) {
if (input[`${key}_clear`]) input[key] = '';
else if (input[key]) input[key] = encrypt(input[key]);
else delete input[key];
}
const updates = Object.entries(input).filter(([k]) => k in DEFAULTS);
for (const [key, value] of updates) {
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
@@ -83,4 +99,10 @@ async function importSmtpFromEnv() {
return true;
}
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv };
/** The saved repo token, decrypted ('' when none). */
async function releaseRepoToken() {
const { release_repo_token } = await rawSettings();
return release_repo_token ? decrypt(release_repo_token) : '';
}
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken };