Events 2.4.0 backend: protocol v2, Linked products, the event feed

- Hub client: register and heartbeat on protocol v2 with the site's
  Ed25519 key (sent on the heartbeat until the Hub has it); falls back to
  v1 for a day if the Hub refuses v2, so the licence always refreshes.
- crosscode.link/1 Connect / Disconnect, both directions, trusted through
  the Hub's cached linkedProducts (ProductLink, LinkNonce).
- GET /api/feed/v1/events from FeedEntry (go-live, closing and selling
  out are changes; deactivated events go in deleted), event.changed to
  connected products, and showing their events (ImportedEvent).
- /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains
  crosscodeEvent and priceRangeCents for the JSON-LD.
- Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 12:24:29 +02:00
co-authored by Claude Opus 5.5
parent 390b80e56e
commit 8a930d07c6
30 changed files with 5874 additions and 17 deletions
+100
View File
@@ -0,0 +1,100 @@
/**
* The endpoints the church's other products call (docs/EVENTS-2.4-PLAN.md §2–4). Contracts
* between products, so outside /api/v2, with errors as `{ message, code }`:
*
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
*
* Mounted before the app's JSON parser: the webhook is verified on its raw bytes.
*/
import express, { type Request, type Response, type Router } from 'express';
import rateLimit from 'express-rate-limit';
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import { hubInstallId, publishOn } from '../feed/context';
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: Request): string | null };
const { enqueueTask } = require('../jobs') as { enqueueTask(name: string, data: object): Promise<unknown> };
/* eslint-enable @typescript-eslint/no-require-imports */
/** The feed is rebuilt before answering when the last refresh is older than this. */
const FRESH_MS = 60 * 1000;
const fail = (res: Response, status: number, code: string, message: string) => res.status(status).json({ message, code });
function sendError(res: Response, e: unknown) {
if (e instanceof LinkError) return fail(res, e.status, e.code, e.message);
console.error('[links]', e);
return fail(res, 500, 'SERVER_ERROR', 'Something went wrong.');
}
const limiter = (max: number) => rateLimit({ windowMs: 5 * 60 * 1000, max, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests, please try again later.', code: 'RATE_LIMITED' } });
export function crossProductRouter(): Router {
const router = express.Router();
const json = express.json({ limit: '16kb' });
router.get(FEED_PATHS.events.replace(/^\/api/, ''), limiter(300), async (req, res) => {
try {
if (!(await publishOn())) return fail(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events (Settings → Linked products).');
if (!(await hubInstallId())) return fail(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
const since = raw ? new Date(raw) : null;
if (raw && (!since || !Number.isFinite(since.getTime()))) return fail(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
if (Date.now() - lastRefresh() > FRESH_MS) await refreshOnce();
res.set('Cache-Control', 'no-store');
return res.json(await feedResponse(since));
} catch (e) {
return sendError(res, e);
}
});
router.post(FEED_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
try {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link) return fail(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
if (!check.ok) return fail(res, 401, check.code, 'The signature doesn\'t match this link.');
let body: unknown;
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
if (!eventChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
if (link.showEvents) await enqueueTask('feed-sync-link', { installId: link.installId });
return res.status(202).json({ accepted: true, fetching: link.showEvents });
} catch (e) {
return sendError(res, e);
}
});
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
try {
return res.json(await acceptConnect(req.body, getClientIp(req)));
} catch (e) {
return sendError(res, e);
}
});
router.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
try {
await acceptDisconnect(req.body, getClientIp(req));
return res.json({ schema: LINK_SCHEMA, type: 'link.disconnected' });
} catch (e) {
return sendError(res, e);
}
});
// A body that isn't JSON (express.json's own error) answers in the same shape.
router.use((err: { type?: string; status?: number }, _req: Request, res: Response, next: (e?: unknown) => void) => {
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') return fail(res, err.status || 400, 'INVALID_REQUEST', 'The body must be JSON (16 kB at most).');
return next(err);
});
return router;
}