From 0adb30402429854760a78c540e31d89cb65dd40a Mon Sep 17 00:00:00 2001 From: joshua Date: Wed, 28 Oct 2026 09:13:30 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 19 +-- README.md | 10 ++ backend/package-lock.json | 4 +- backend/package.json | 2 +- backend/src/index.js | 5 +- backend/src/routes/admin.js | 35 +++++- backend/src/utils/releaseSync.js | 149 +++++++++++++++++++++++ backend/src/utils/settings.js | 40 ++++-- backend/tests/releaseSync.test.js | 63 ++++++++++ docs/hub-protocol.md | 5 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- frontend/src/app/(hub)/releases/page.tsx | 80 ++++++++++-- 13 files changed, 380 insertions(+), 38 deletions(-) create mode 100644 backend/src/utils/releaseSync.js create mode 100644 backend/tests/releaseSync.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 776af06..1ce02a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,13 +5,19 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.4.0] - 2026-10-28 + ### Added -- **Releases page** — each Cross Events version with what's new in it, and whether it's **urgent** - (a security or serious bug fix). Installs on an older version get the notes for every version - they'd get, so the church can decide whether to ask for the update; urgent ones can't be put off. - The newest release is the latest version (it used to be set on the Settings page; the version - that was set there becomes the first release, without notes). +- **Releases from git** — every `v1.2.3` tag of the Cross Events repository is a release, and the + newest tag is the latest version: no more setting it by hand. What's new in each version comes + from the repo's `WHATS-NEW.md` (written for churches; `urgent` or `security` in a version's heading + marks a security or serious bug fix). Synced every 15 minutes and with **Sync now** on the new + **Releases** page, which shows each version, its notes and how many installs run it. Installs on an + older version get the notes for every version they'd get, so the church can decide whether to ask + for the update; urgent ones can't be put off. Set to the hope-events repository by default; a + token is only needed if it becomes private. With the repository cleared, releases are added by + hand on the same page. - **Notices page** — write a message for every install or chosen ones: a **banner** on their site for site admins and supervisors (from and until a time, e.g. planned maintenance), an **email** to the customer and the site's admin contact, or both. Banners can be edited or ended early. @@ -22,8 +28,7 @@ versions follow [Semantic Versioning](https://semver.org/). - Settings → "Releases and alerts" is now "Alerts"; the latest version follows the Releases page. -Needs Cross Events 1.4x with the matching changes to show the notes and notices; older installs keep -working and ignore them. +Cross Events 1.46.2 shows the notes and notices; older installs keep working and ignore them. ## [1.3.0] - 2026-10-28 diff --git a/README.md b/README.md index 6486fef..5fbaadf 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,16 @@ The first login sets up two-factor with an authenticator app (required). To try it with Cross Events locally, point the install at the Hub with `HUB_URL=http://localhost:5200` and `HUB_PUBLIC_KEY` (the public key shown in Hub → Settings) in Cross Events' `backend/.env`. +## Releases and notices + +- **Releases** come from git: every `v1.2.3` tag of `joshua/hope-events` is a release, the newest is + the latest version, and the notes churches see come from `WHATS-NEW.md` in that repo as of the + newest tag. The Hub checks every 15 minutes (and on **Sync now**, Releases page). So releasing + Cross Events is: write the version's section in `WHATS-NEW.md`, tag, push — installs see the + update with their next heartbeat. +- **Notices** (Notices page) are banners on churches' sites for their admins and supervisors, emails + to them, or both — e.g. planned maintenance. + ## The licence signing key Licences are tokens signed with an Ed25519 key. **The private key exists only on the Hub server**; diff --git a/backend/package-lock.json b/backend/package-lock.json index de2c778..20d3243 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "1.3.0", + "version": "1.4.0", "hasInstallScript": true, "dependencies": { "@prisma/adapter-pg": "^7.10.1", diff --git a/backend/package.json b/backend/package.json index af5d62f..b309b76 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "1.3.0", + "version": "1.4.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/backend/src/index.js b/backend/src/index.js index a1f2dc1..3255f31 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -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); } diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 24ecc20..525f211 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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)); diff --git a/backend/src/utils/releaseSync.js b/backend/src/utils/releaseSync.js new file mode 100644 index 0000000..7499ff9 --- /dev/null +++ b/backend/src/utils/releaseSync.js @@ -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(//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 }; diff --git a/backend/src/utils/settings.js b/backend/src/utils/settings.js index d804385..c964962 100644 --- a/backend/src/utils/settings.js +++ b/backend/src/utils/settings.js @@ -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" (_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); _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 }; diff --git a/backend/tests/releaseSync.test.js b/backend/tests/releaseSync.test.js new file mode 100644 index 0000000..fffaf21 --- /dev/null +++ b/backend/tests/releaseSync.test.js @@ -0,0 +1,63 @@ +// Releases from git: reading the repo address and WHATS-NEW.md. +jest.mock('../src/config/db', () => ({})); + +const { parseRepoUrl, parseNotes } = require('../src/utils/releaseSync'); + +test('the repository address becomes the Gitea API', () => { + expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua/hope-events')).toEqual({ api: 'https://c-git.crosscode.co.za/api/v1/repos/joshua/hope-events', owner: 'joshua', repo: 'hope-events' }); + expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua/hope-events.git/').api).toBe('https://c-git.crosscode.co.za/api/v1/repos/joshua/hope-events'); + expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua')).toBeNull(); + expect(parseRepoUrl('ftp://x/y/z')).toBeNull(); + expect(parseRepoUrl('')).toBeNull(); +}); + +describe('WHATS-NEW.md', () => { + const md = `# What's new in Cross Events + +Intro text that isn't a release. + + + +## 1.46.2 — urgent + +- **See what's new** before you update, on the + Licence page. +- Uses \`code\` and [a link](https://example.com). + +## [1.46.1] - 2026-10-28 + +Behind-the-scenes maintenance. +Nothing changes for you. + +## v1.46.0 (security fix) + +### Volunteers +- Rosters + - Swaps +`; + const notes = parseNotes(md); + + test('one section per version; comments and the title are skipped', () => { + expect(Object.keys(notes).sort()).toEqual(['1.46.0', '1.46.1', '1.46.2']); + }); + + test('"urgent" or "security" in the heading marks it urgent', () => { + expect(notes['1.46.2'].urgent).toBe(true); + expect(notes['1.46.1'].urgent).toBe(false); + expect(notes['1.46.0'].urgent).toBe(true); + }); + + test('markup is removed, wrapped lines joined, list items kept', () => { + expect(notes['1.46.2'].notes).toBe("- See what's new before you update, on the Licence page.\n- Uses code and a link."); + expect(notes['1.46.1'].notes).toBe('Behind-the-scenes maintenance. Nothing changes for you.'); + expect(notes['1.46.0'].notes).toBe('Volunteers\n- Rosters\n- Swaps'); + }); + + test('no file means no notes', () => { + expect(parseNotes('')).toEqual({}); + expect(parseNotes(null)).toEqual({}); + }); +}); diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index eac96af..b0b51f8 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -117,8 +117,9 @@ X-Hub-Signature: } ``` -- **`releases`** — what's new in each version, written by Joshua on the Hub's Releases page, so the - church can decide whether to ask for the update. `notes` is plain text; lines starting with `- ` are +- **`releases`** — what's new in each version, so the church can decide whether to ask for the + update. The Hub takes the versions from the Cross Events repository's `v*` tags and the notes from + its `WHATS-NEW.md`. `notes` is plain text; lines starting with `- ` are a list. `urgent` marks security or serious bug fixes: the install shows those in red and doesn't let admins put them off. The highest release is `latestVersion`. - **`notices`** — banners Joshua posts on the Hub's Notices page (`level`: `info`, `maintenance` or diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0de8f29..fda3cb3 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "1.3.0", + "version": "1.4.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index e4848d3..d3d55bf 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "1.3.0", + "version": "1.4.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/releases/page.tsx b/frontend/src/app/(hub)/releases/page.tsx index e26dd4b..3a5e65e 100644 --- a/frontend/src/app/(hub)/releases/page.tsx +++ b/frontend/src/app/(hub)/releases/page.tsx @@ -1,9 +1,9 @@ "use client"; import React, { useCallback, useEffect, useState } from "react"; -import { ShieldAlert } from "lucide-react"; +import { GitBranch, RefreshCw, ShieldAlert } from "lucide-react"; import { api, errorText } from "@/lib/api"; -import { fmtDate } from "@/lib/format"; +import { ago, fmtDate } from "@/lib/format"; import type { Release } from "@/lib/types"; import { Badge, Loading, Message, PageTitle, ReleaseNotes } from "@/components/ui"; @@ -45,6 +45,62 @@ function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSav ); } +type Source = { release_repo_url: string; release_notes_path: string; release_repo_token_set: string; release_synced_at: string; release_sync_error: string }; + +/** Where releases come from: the git repository's tags and WHATS-NEW.md (synced every 15 minutes). */ +function GitSource({ source, onSaved, setMsg }: { source: Source; onSaved: () => void; setMsg: (m: Msg) => void }) { + const [form, setForm] = useState({ url: source.release_repo_url, path: source.release_notes_path || "WHATS-NEW.md", token: "", clearToken: false }); + const [busy, setBusy] = useState(false); + + const syncNow = async (saved = false) => { + try { + const r = await api<{ tags: number; added: number; updated: number; removed: number; latest: string | null }>("/api/admin/releases/sync", { method: "POST" }); + setMsg({ type: "ok", text: `${saved ? "Saved and synced" : "Synced"}: ${r.tags} version tags, ${r.added} new, ${r.updated} updated, ${r.removed} removed. Latest is ${r.latest || "not set"}.` }); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + onSaved(); + }; + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setMsg(null); + try { + await api("/api/admin/settings", { method: "PUT", body: { settings: { release_repo_url: form.url.trim(), release_notes_path: form.path.trim(), release_repo_token: form.token, release_repo_token_clear: form.clearToken } } }); + setForm({ ...form, token: "", clearToken: false }); + if (form.url.trim()) await syncNow(true); + else { setMsg({ type: "ok", text: "Saved. Releases are added by hand now." }); onSaved(); } + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + setBusy(false); + }; + + return ( +
+
+ +

From git

+ {source.release_repo_url && Last synced {ago(source.release_synced_at || null)}} + {source.release_repo_url && ( + + )} +
+

Every v1.2.3 tag is a release, and the newest tag is the latest version. The notes come from the file below as of that tag: a ## 1.2.3 heading per version, with urgent or security in the heading for an urgent release. Checked every 15 minutes. Leave the address blank to add releases by hand.

+
+
setForm({ ...form, url: e.target.value })} />
+
setForm({ ...form, path: e.target.value })} />
+
+
+ + setForm({ ...form, token: e.target.value })} /> + {source.release_repo_token_set && } +
+ {source.release_sync_error &&

{source.release_sync_error}

} + +
+ ); +} + /** Cross Events versions and what's new in each. The newest is the latest version installs are offered. */ export default function ReleasesPage() { const [releases, setReleases] = useState(null); @@ -53,7 +109,12 @@ export default function ReleasesPage() { const [editing, setEditing] = useState(null); const [busy, setBusy] = useState(false); - const load = useCallback(() => api("/api/admin/releases").then(setReleases).catch(e => setMsg({ type: "err", text: errorText(e) })), []); + const [source, setSource] = useState(null); + const load = useCallback(() => { + api("/api/admin/releases").then(setReleases).catch(e => setMsg({ type: "err", text: errorText(e) })); + api<{ settings: Source }>("/api/admin/settings").then(r => setSource(r.settings)).catch(() => {}); + }, []); + const fromGit = !!source?.release_repo_url; useEffect(() => { load(); }, [load]); const body = (f: Form) => ({ version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null }); @@ -84,9 +145,10 @@ export default function ReleasesPage() { { setAdding(true); setEditing(null); }}>Add release} + actions={!adding && !fromGit && source && } /> {msg &&
} + {source && } {adding &&

New release

save(f)} onCancel={() => setAdding(false)} />
} {!releases ? : releases.length === 0 ?

No releases yet. Add the version installs should be on.

: ( @@ -102,10 +164,12 @@ export default function ReleasesPage() { {i === 0 && } {r.urgent && Urgent} {fmtDate(r.releasedAt, false)} · {r.installs} install{r.installs === 1 ? "" : "s"} on it - - - - + {!fromGit && ( + + + + + )}