Merge branch 'feat/link-public-key'

This commit is contained in:
2026-11-18 13:02:21 +02:00
12 changed files with 174 additions and 14 deletions
+16
View File
@@ -5,6 +5,22 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.2.0] - unreleased
For Cross Events 2.4.0 (crosscode-platform `docs/EVENTS-2.4-PLAN.md` §1): installs move to
protocol v2 without their licence key. Contracts 1.4.0 (`backend/vendor/`).
### Added
- **A public key on the v2 heartbeat** (`publicKey`). The Hub saves it when the install has none,
so an install that registered with v1 (every Cross Events before 2.4.0) becomes a v2 install its
siblings can link to. The reply says `publicKeyStatus`: `saved`, `matches` or `mismatch`. A
different key never fails the heartbeat (the licence keeps refreshing): the saved key stays and
an alert opens on the install.
- **Clear public key** on an install's page (two-factor again, audited as
`install_public_key_cleared`), for a site whose server was restored or rebuilt with a new key.
The page also shows whether the site's key is saved.
## [2.1.1] - 2026-11-18
### Fixed
+6 -6
View File
@@ -1,16 +1,16 @@
{
"name": "events-hub-backend",
"version": "2.1.1",
"version": "2.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.1.1",
"version": "2.2.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.3.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.4.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -609,9 +609,9 @@
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.3.0",
"resolved": "file:vendor/crosscode-contracts-1.3.0.tgz",
"integrity": "sha512-T9RVPg3WDhqvEldqToPfp/6HSce0K26BGNvbM0Ksz8uvteXk/OfdARF3mwlDMcmsrp32pQ4w5D62GMTziuSX8A==",
"version": "1.4.0",
"resolved": "file:vendor/crosscode-contracts-1.4.0.tgz",
"integrity": "sha512-WJ2LwSBhRmZ7nYTKo4Q1bPmElZew1ZtbO6XZlxopBWtJmpXbv9SSHKoYWS3sVwnXrewPJrAMe2ur8IofE9RsWg==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.1.1",
"version": "2.2.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -20,7 +20,7 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.3.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.4.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
+16
View File
@@ -19,6 +19,7 @@ const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('../utils/releaseSync');
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
const { requireTotp } = require('../utils/jobs');
const router = express.Router();
router.use(protect);
@@ -270,6 +271,21 @@ router.put('/installs/:id', wrap(async (req, res) => {
res.json({ id: install.id, notes: install.notes });
}));
// Hub 2.2.0: forget an install's public key (e.g. its server was restored and made a new one), so
// the next heartbeat's key is saved. Its siblings stop listing it until then, and their links to
// it must be connected again. Needs two-factor again, like an uninstall.
router.post('/installs/:id/public-key/clear', wrap(async (req, res) => {
requireTotp(req.admin, req.body?.totp);
const install = await prisma.install.findUnique({ where: { id: req.params.id } });
if (!install) throw bad('Install not found', 404);
const now = new Date();
await prisma.install.update({ where: { id: install.id }, data: { publicKey: null } });
await prisma.installEvent.updateMany({ where: { installId: install.id, type: 'public_key_mismatch', resolvedAt: null }, data: { resolvedAt: now } });
await prisma.installEvent.create({ data: { installId: install.id, type: 'public_key', level: 'info', message: 'Public key cleared by the provider; the next heartbeat saves the install\'s current key.', resolvedAt: now } });
await audit(req, 'install_public_key_cleared', install.id);
res.json({ cleared: true });
}));
// ─── Alerts and history ───────────────────────────────────────────────────────
router.get('/events', wrap(async (req, res) => {
+35
View File
@@ -23,6 +23,7 @@ const { noticesForInstall } = require('../utils/notices');
const ai = require('../utils/ai');
const { PRODUCT_NAMES } = require('../utils/products');
const { hub } = require('@crosscode/contracts');
const { ed25519PublicFromPem } = require('@crosscode/contracts/signing');
const { PROTOCOL_VERSIONS, isV2, parseV2, linkedProductsFor } = require('../utils/protocol');
const router = express.Router();
@@ -175,6 +176,37 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
}
});
/** The same key, ignoring line endings and surrounding whitespace. */
function samePem(a, b) {
const norm = s => String(s || '').replace(/\r\n/g, '\n').trim();
return norm(a) === norm(b);
}
/**
* A public key sent on a v2 heartbeat (Hub 2.2.0): `saved` when the install had none, `matches`,
* or `mismatch` (the saved key stays; an alert is opened once). Lets an install that registered
* with protocol v1 move to v2 without its licence key. Never fails the heartbeat: the licence
* must keep refreshing whatever happens to the key.
*/
async function acceptPublicKey(install, pem, now) {
try {
ed25519PublicFromPem(pem);
} catch {
return 'mismatch';
}
if (!install.publicKey) {
await prisma.install.update({ where: { id: install.id }, data: { publicKey: `${pem.replace(/\r\n/g, '\n').trim()}\n` } });
await prisma.installEvent.create({ data: { installId: install.id, type: 'public_key', level: 'info', message: 'Public key saved: the church\'s other products can now link to this install.', resolvedAt: now } });
return 'saved';
}
if (samePem(install.publicKey, pem)) return 'matches';
const open = await prisma.installEvent.findFirst({ where: { installId: install.id, type: 'public_key_mismatch', resolvedAt: null } });
if (!open) {
await prisma.installEvent.create({ data: { installId: install.id, type: 'public_key_mismatch', level: 'warning', message: 'The install sent a different public key from the one saved. Linked products keep using the saved key. If the server was restored or rebuilt, clear the saved key on this install\'s page.' } });
}
return 'mismatch';
}
router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
@@ -200,12 +232,15 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
}
}
const publicKeyStatus = v2 && body.publicKey ? await acceptPublicKey(install, body.publicKey, now) : null;
res.json({
licence: await tokenFor(install),
...(await releaseInfo(install, version || install.version, { v2 })),
notices: await noticesForInstall(install.id, now),
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
serverTime: now.toISOString(),
...(publicKeyStatus ? { publicKeyStatus } : {}),
});
} catch (e) {
console.error('[heartbeat]', e);
+53
View File
@@ -239,6 +239,59 @@ describe('heartbeat', () => {
expect(Object.keys(json).sort()).toEqual(['latestVersion', 'licence', 'notices', 'releases', 'serverTime']);
});
describe('public key on the heartbeat (Hub 2.2.0)', () => {
const v1Events = async () => {
const r = eventsRegistration();
const { json } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.3.1' } });
return json;
};
test('an install registered with v1 moves to v2 with its key, and its siblings then list it', async () => {
const reg = await v1Events();
const { json: website } = await register(websiteRegistration());
const key = pem();
const res = await signed('/installs/heartbeat', reg, { ...sample('hub-heartbeat-events.json'), publicKey: key });
const json = await res.json();
expect(res.status).toBe(200);
expect(hub.heartbeatResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
expect(json.publicKeyStatus).toBe('saved');
expect(json.linkedProducts.map(l => l.product)).toEqual(['website']);
expect(mockDb.t.installs.find(i => i.id === reg.installId).publicKey.trim()).toBe(key.trim());
const fromWebsite = await (await signed('/installs/heartbeat', website, sample('hub-heartbeat-website.json'))).json();
expect(fromWebsite.linkedProducts.map(l => [l.product, l.installId])).toEqual([['events', reg.installId]]);
});
test('the same key again matches, also with Windows line endings', async () => {
const reg = await v1Events();
const key = pem();
await signed('/installs/heartbeat', reg, { ...sample('hub-heartbeat-events.json'), publicKey: key });
const crlfKey = key.split(String.fromCharCode(10)).join(String.fromCharCode(13, 10));
const json = await (await signed('/installs/heartbeat', reg, { ...sample('hub-heartbeat-events.json'), publicKey: crlfKey })).json();
expect(json.publicKeyStatus).toBe('matches');
});
test('a different key keeps the saved one, raises one alert and never fails the heartbeat', async () => {
const reg = await v1Events();
const first = pem();
await signed('/installs/heartbeat', reg, { ...sample('hub-heartbeat-events.json'), publicKey: first });
for (let i = 0; i < 2; i++) {
const res = await signed('/installs/heartbeat', reg, { ...sample('hub-heartbeat-events.json'), publicKey: pem() });
expect(res.status).toBe(200);
const json = await res.json();
expect(json.publicKeyStatus).toBe('mismatch');
expect(json.licence).toBeTruthy();
}
expect(mockDb.t.installs.find(i => i.id === reg.installId).publicKey.trim()).toBe(first.trim());
expect(mockDb.t.events.filter(e => e.type === 'public_key_mismatch').length).toBeGreaterThanOrEqual(1);
});
test('a heartbeat without a key has no publicKeyStatus', async () => {
const { json: reg } = await register(eventsRegistration());
const json = await (await signed('/installs/heartbeat', reg, sample('hub-heartbeat-events.json'))).json();
expect(json).not.toHaveProperty('publicKeyStatus');
});
});
test('an unsigned heartbeat is refused', async () => {
const { json: reg } = await register(eventsRegistration());
const res = await post('/installs/heartbeat', sample('hub-heartbeat-events.json'), { 'X-Hub-Install': reg.installId, 'X-Hub-Timestamp': new Date().toISOString(), 'X-Hub-Signature': 'nope' });
Binary file not shown.
Binary file not shown.
+21 -3
View File
@@ -332,6 +332,24 @@ what's needed) until the church's install of that product runs that version or l
**AI.** The monthly cap and markup are the church's, shared by all its installs: a call from any of
them counts what all of them used this month.
**Moving an install to v2** (e.g. Cross Events 2.4.0): register again with `protocolVersion: 2`,
the product and a public key (same licence and address: same install id, new secret), then send v2
heartbeats. Nothing on the Hub needs changing.
**Moving an install to v2** (e.g. Cross Events 2.4.0, Hub 2.2.0+): an install that registered with
v1 just starts sending v2 heartbeats, with its Ed25519 public key (PEM) in `publicKey`. It doesn't
need its licence key again (Cross Events never stored it). The heartbeat is already signed with the
install secret, so the Hub knows whose key it is. The reply says what happened in
`publicKeyStatus`:
| `publicKeyStatus` | Meaning |
|-------------------|---------|
| `saved` | The Hub had no key for the install and saved this one; the church's other installs list it from their next heartbeat |
| `matches` | The Hub already has this key (line endings and surrounding whitespace don't count) |
| `mismatch` | The Hub has a **different** key and keeps it: an alert opens on the install, and Joshua can **Clear public key** on its page (two-factor again) when the server was restored or rebuilt; the next heartbeat then saves the new key |
A key problem never fails the heartbeat: the licence keeps refreshing whatever happens to the key.
An install keeps sending `publicKey` until it gets `saved` or `matches`. A Hub before 2.2.0 ignores
the field (no `publicKeyStatus`), so the install isn't listed to its siblings until the Hub is
updated. Registering again with `protocolVersion: 2`, the product and a public key (same licence
and address: same install id, new secret) also works, as before.
**Connecting two installs** (Settings → Linked products → Connect) is between the installs, not
through the Hub: `crosscode.link/1` in `@crosscode/contracts` (`src/link.ts`), with each side
checking the other against the `linkedProducts` it has cached from the Hub.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.1.1",
"version": "2.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.1.1",
"version": "2.2.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.1.1",
"version": "2.2.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
@@ -14,6 +14,7 @@ import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
type Detail = {
id: string; name: string; url: string; version: string | null; protocolVersion: number; timezone: string | null; notes: string | null;
publicKey: string | null;
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
health: Health | null; stats: Stats | null;
@@ -39,6 +40,7 @@ export default function InstallPage() {
const { id } = useParams<{ id: string }>();
const [d, setD] = useState<Detail | null>(null);
const [notes, setNotes] = useState("");
const [keyTotp, setKeyTotp] = useState("");
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(() => api<Detail>(`/api/admin/installs/${id}`).then(x => { setD(x); setNotes(x.notes || ""); }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
@@ -63,6 +65,16 @@ export default function InstallPage() {
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const clearKey = async () => {
if (!window.confirm("Forget this site's public key? The church's other products stop listing it until its next heartbeat, and their links to it must be connected again.")) return;
try {
await api(`/api/admin/installs/${id}/public-key/clear`, { method: "POST", body: { totp: keyTotp } });
setKeyTotp("");
setMsg({ type: "ok", text: "Public key cleared. The next heartbeat saves the site's current key." });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
@@ -107,6 +119,16 @@ export default function InstallPage() {
<p className="mt-2 text-xs text-slate-500">{d.protocolVersion >= 2 ? "This site is told about the products listed to it in each heartbeat reply (Linked products), so it can connect to them." : "This site uses protocol 1 (Cross Events before 2.4), so it isn't told about the others yet."}</p>
</>
)}
<div className="mt-3 border-t border-slate-100 pt-3">
<Row k="This site's public key" v={d.publicKey ? "saved" : d.protocolVersion >= 2 ? "none yet (saved with its next heartbeat)" : "none (protocol 1)"} />
{d.publicKey && (
<form className="mt-2 flex flex-wrap items-end gap-2" onSubmit={e => { e.preventDefault(); clearKey(); }}>
<p className="w-full text-xs text-slate-500">Only when the site&apos;s server was restored or rebuilt and the history below says it sent a different key: clearing lets its next heartbeat save the new one.</p>
<div><label className="label" htmlFor="k-t">Two-factor code</label><input id="k-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={keyTotp} onChange={e => setKeyTotp(e.target.value)} /></div>
<button className="btn-danger">Clear public key</button>
</form>
)}
</div>
</div>
<div className="grid gap-6 md:grid-cols-2">