/** * 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/church/v1/changed church.changed from the church's Accounts (3.7.0) * 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 { CHURCH_PATHS, churchChangedSchema, 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'; import { churchChanged } from '../accounts/church'; /* 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 }; /* 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); } }); // 3.7.0: the church profile changed in Accounts (its brand style, footer details): fetch it again. router.post(CHURCH_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 || link.product !== 'accounts') return fail(res, 404, 'NOT_LINKED', 'This site has no link with that Accounts.'); 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 (!churchChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', "That isn't a church.changed message."); churchChanged(); return res.status(202).json({ accepted: true }); } 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; }