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
+1
View File
@@ -24,6 +24,7 @@ import './resources/checkin';
import './resources/auth';
import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
const pkg = require('../../package.json') as { version: string };
@@ -6,6 +6,7 @@ import { single } from '../paging';
import { absoluteUrl, id, idParams, isoDate } from '../schemas';
import * as details from '../../services/eventDetails';
import { managedEvent } from './eventsManage';
import { crosscodeEventFor } from '../../feed/build';
/* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */
const campusScope = require('../../utils/campusScope') as {
@@ -35,9 +36,15 @@ export const full = defineRoute({
response: single(managedEvent.extend({
form: z.looseObject({ id, isRequired: z.boolean(), fields: z.array(z.looseObject({ id, type: z.string(), label: z.string() })) }).nullable(),
attachments: z.array(z.looseObject({ id, originalName: z.string(), url: z.string().nullable() })),
crosscodeEvent: z.looseObject({ schema: z.literal('crosscode.event/1'), id }).nullable()
.describe('The event as crosscode.event/1 (2.4.0), what its page builds its schema.org JSON-LD from (@crosscode/seo). The same shape the event feed publishes.'),
priceRangeCents: z.object({ lowCents: z.number().int(), highCents: z.number().int() }).nullable()
.describe('The lowest and highest current ticket prices in cents, for the JSON-LD price range (null when free)'),
})),
async handler({ params, user, req }) {
return { data: plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req))) };
const detail = plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req)));
const built = await crosscodeEventFor(params.id).catch(() => null);
return { data: { ...detail, crosscodeEvent: built?.event ?? null, priceRangeCents: built?.priceRangeCents ?? null } };
},
});
@@ -0,0 +1,277 @@
import { z } from 'zod';
import { defineRoute } from '../route';
import { ApiError, notFound } from '../errors';
import { single } from '../paging';
import { iso, isoDate } from '../schemas';
import { connectTo, disconnectFrom, LinkError } from '../../links/connect';
import { linkedProducts, publicKeyStatus } from '../../links/store';
import { hubInstallId, PUBLISH_KEY, publishOn } from '../../feed/context';
import { syncLink } from '../../feed/sync';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../../config/db');
const { invalidate } = require('../../utils/settingsCache') as { invalidate(key?: string): void };
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Settings → Linked products (2.4.0, docs/EVENTS-2.4-PLAN.md §2, §4, §6): the church's other
* products as the Hub lists them, Connect / Disconnect, "Show events from" per product and
* "Publish my events" for this site. And, for the public pages, the events imported from them.
*/
const PRODUCT_NAMES: Record<string, string> = { events: 'Cross Events', website: 'Church Website', app: 'Church App', accounts: 'Accounts' };
/** Products that publish events (Accounts has none). */
const EVENT_PRODUCTS = new Set(['website', 'app']);
const installParams = z.object({ installId: z.uuid().describe("The product's Hub install id") });
function asApiError(e: unknown): never {
if (e instanceof LinkError) {
const code = e.status === 404 ? 'NOT_FOUND' : e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : e.status === 409 ? 'CONFLICT' : 'VALIDATION_FAILED';
throw new ApiError(code, e.message);
}
throw e;
}
const linkState = z.object({
connectedAt: isoDate,
connectedBy: z.string().nullable().describe('Who pressed Connect here; null when the other product connected'),
showEvents: z.boolean(),
lastSyncAt: isoDate.nullable(),
lastGoodAt: isoDate.nullable().describe('When its events were last fetched successfully'),
lastSyncError: z.string().nullable(),
importedEvents: z.number().int(),
});
const productRow = z.object({
installId: z.string(),
product: z.string(),
name: z.string(),
url: z.string(),
listed: z.boolean().describe('In the list the Hub last gave (false: connected before, no longer listed)'),
publishesEvents: z.boolean(),
link: linkState.nullable().describe('null = not connected'),
});
type LinkRow = {
installId: string; product: string; url: string; connectedAt: Date; connectedById: string | null; showEvents: boolean;
lastSyncAt: Date | null; lastGoodAt: Date | null; lastSyncError: string | null; _count: { importedEvents: number };
};
async function overview() {
const [listed, links, installId, publish, keyStatus] = await Promise.all([
linkedProducts(),
prisma.productLink.findMany({ include: { _count: { select: { importedEvents: true } } } }) as Promise<LinkRow[]>,
hubInstallId(),
publishOn(),
publicKeyStatus(),
]);
const people = new Map<string, string>(
(await prisma.user.findMany({ where: { id: { in: links.map((l) => l.connectedById).filter(Boolean) as string[] } }, select: { id: true, name: true } }))
.map((u: { id: string; name: string }) => [u.id, u.name]),
);
const byId = new Map(links.map((l) => [l.installId, l]));
const ids = [...new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)])];
const products = ids.map((id) => {
const hubRow = listed.find((l) => l.installId === id);
const link = byId.get(id);
const product = hubRow?.product ?? link!.product;
return {
installId: id,
product,
name: PRODUCT_NAMES[product] ?? product,
url: hubRow?.url ?? link!.url,
listed: !!hubRow,
publishesEvents: EVENT_PRODUCTS.has(product),
link: link ? {
connectedAt: iso(link.connectedAt),
connectedBy: link.connectedById ? people.get(link.connectedById) ?? 'A deleted account' : null,
showEvents: link.showEvents,
lastSyncAt: iso(link.lastSyncAt),
lastGoodAt: iso(link.lastGoodAt),
lastSyncError: link.lastSyncError,
importedEvents: link._count.importedEvents,
} : null,
};
});
return {
hubConnected: !!installId,
// "saved" / "matches": the Hub has this site's key, so the others can link to it.
keyKnownToHub: keyStatus === 'saved' || keyStatus === 'matches',
keyMismatch: keyStatus === 'mismatch',
publishEvents: publish,
products,
};
}
const overviewSchema = z.object({
hubConnected: z.boolean(),
keyKnownToHub: z.boolean().describe("The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it"),
keyMismatch: z.boolean().describe('The Hub has a different key for this site (ask the provider to clear it)'),
publishEvents: z.boolean(),
products: z.array(productRow),
});
export const getLinkedProducts = defineRoute({
method: 'get',
path: '/linked-products',
tag: 'Linked products',
summary: "The church's other products",
description: 'As the Hub last listed them (with each heartbeat), with whether each is connected and its events shown here.',
access: 'admin',
response: single(overviewSchema),
async handler() {
return { data: await overview() };
},
});
export const updateFeedSettings = defineRoute({
method: 'put',
path: '/linked-products/settings',
tag: 'Linked products',
summary: 'Publish my events (on or off)',
description: 'Whether this site publishes its public events for the church\'s other products (GET /api/feed/v1/events).',
access: 'admin',
body: z.object({ publishEvents: z.boolean() }),
response: single(overviewSchema),
async handler({ body, user, req }) {
await prisma.appSetting.upsert({ where: { key: PUBLISH_KEY }, update: { value: String(body.publishEvents) }, create: { key: PUBLISH_KEY, value: String(body.publishEvents) } });
invalidate(PUBLISH_KEY);
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'feed_publish_toggled', targetType: 'setting', targetId: PUBLISH_KEY, metadata: { publishEvents: body.publishEvents }, ip: getClientIp(req) });
return { data: await overview() };
},
});
export const connect = defineRoute({
method: 'post',
path: '/linked-products/:installId/connect',
tag: 'Linked products',
summary: 'Connect to one of the church\'s products',
description: 'Sets up a signed link with it (crosscode.link/1). Both products must be in each other\'s list from the Hub. Connecting again replaces the link\'s secret.',
access: 'admin',
params: installParams,
response: single(overviewSchema),
async handler({ params, user, req }) {
await connectTo(params.installId, { id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError);
return { data: await overview() };
},
});
export const disconnect = defineRoute({
method: 'post',
path: '/linked-products/:installId/disconnect',
tag: 'Linked products',
summary: 'Disconnect a product',
description: 'Ends the link on both sides (the other product is told when it can be reached) and removes its events from this site.',
access: 'admin',
params: installParams,
response: single(overviewSchema.extend({ otherSideTold: z.boolean(), problem: z.string().nullable() })),
async handler({ params, user, req }) {
const r = await disconnectFrom(params.installId, { id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError);
return { data: { ...(await overview()), otherSideTold: r.siblingTold, problem: r.message } };
},
});
export const updateLink = defineRoute({
method: 'put',
path: '/linked-products/:installId',
tag: 'Linked products',
summary: 'Show events from a connected product (on or off)',
description: 'On: its events are fetched now and every 15 minutes, and shown on the public pages. Off: they are removed from this site.',
access: 'admin',
params: installParams,
body: z.object({ showEvents: z.boolean() }),
response: single(overviewSchema),
async handler({ params, body, user, req }) {
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
if (!link) throw notFound('That connected product');
if (body.showEvents && !EVENT_PRODUCTS.has(link.product)) throw new ApiError('VALIDATION_FAILED', `${PRODUCT_NAMES[link.product] ?? link.product} has no events to show.`);
const updated = await prisma.productLink.update({ where: { installId: link.installId }, data: { showEvents: body.showEvents, ...(body.showEvents ? {} : { lastGoodAt: null }) } });
if (body.showEvents) await syncLink(updated);
else await prisma.importedEvent.deleteMany({ where: { linkId: link.installId } });
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'feed_show_toggled', targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, showEvents: body.showEvents }, ip: getClientIp(req) });
return { data: await overview() };
},
});
export const syncNow = defineRoute({
method: 'post',
path: '/linked-products/:installId/sync',
tag: 'Linked products',
summary: 'Fetch a product\'s events now',
access: 'admin',
params: installParams,
response: single(overviewSchema),
async handler({ params }) {
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
if (!link) throw notFound('That connected product');
await syncLink(link);
return { data: await overview() };
},
});
// ─── Public: events from linked products ─────────────────────────────────────
const crosscodeEvent = z.looseObject({
schema: z.literal('crosscode.event/1'),
id: z.string(),
title: z.string(),
startsAt: isoDate,
endsAt: isoDate,
}).describe('The event as crosscode.event/1, as the other product published it');
const linkedEvent = z.object({
key: z.string().describe('"<product>:<id>", unique across products'),
product: z.string(),
productName: z.string(),
event: crosscodeEvent,
});
type ImportedRow = { key: string; payload: { origin: { product: string } } & Record<string, unknown>; campusSlug: string | null };
const toLinked = (r: ImportedRow) => ({ key: r.key, product: r.payload.origin.product, productName: PRODUCT_NAMES[r.payload.origin.product] ?? r.payload.origin.product, event: r.payload as unknown as z.input<typeof crosscodeEvent> });
export const listLinkedEvents = defineRoute({
method: 'get',
path: '/linked-events',
tag: 'Events',
summary: "Upcoming events from the church's other products",
description: 'Read-only copies of the events of connected products shown here (Settings → Linked products), soonest first. Each links back to its own page.',
access: 'public',
query: z.object({
campus: z.string().max(64).optional().describe("A campus slug (its events, church-wide ones and ones for a campus this site doesn't have), or 'all' for church-wide only"),
limit: z.coerce.number().int().min(1).max(100).default(50),
}),
response: single(z.array(linkedEvent)),
async handler({ query }) {
const now = new Date();
const rows: ImportedRow[] = await prisma.importedEvent.findMany({
where: { endsAt: { gte: now }, link: { showEvents: true } },
orderBy: [{ startsAt: 'asc' }, { key: 'asc' }],
take: 300,
});
let list = rows;
if (query.campus) {
const ours = new Set<string>((await prisma.campus.findMany({ select: { slug: true } })).map((c: { slug: string }) => c.slug));
list = rows.filter((r) => !r.campusSlug || !ours.has(r.campusSlug) || (query.campus !== 'all' && r.campusSlug === query.campus));
}
return { data: list.slice(0, query.limit).map(toLinked) };
},
});
export const getLinkedEvent = defineRoute({
method: 'get',
path: '/linked-events/:product/:id',
tag: 'Events',
summary: "One event from another of the church's products",
access: 'public',
params: z.object({ product: z.enum(['website', 'app']).describe('The product the event comes from'), id: z.uuid().describe("The event's id in that product") }),
response: single(linkedEvent.extend({ lastSyncedAt: isoDate.nullable().describe('When the copy was last refreshed from its product') })),
async handler({ params }) {
const row = await prisma.importedEvent.findFirst({ where: { key: `${params.product}:${params.id}`, link: { showEvents: true } }, include: { link: { select: { lastGoodAt: true } } } });
if (!row) throw notFound('That event');
return { data: { ...toLinked(row), lastSyncedAt: iso(row.link.lastGoodAt) } };
},
});