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
+3 -1
View File
@@ -119,7 +119,9 @@ Managed in the Payments tab (through `/api/v2/payments/providers/settings` and `
| `VOLUNTEER_JOBS_ENABLED` (env) | `true` | The `volunteers` job (every 15 minutes) that sends volunteer reminders the day before a shift. |
| `WEBHOOKS_JOBS_ENABLED` (env) | `true` | The `webhooks` job (every minute): sends deliveries that are due (retries), picks up sends cut off by a restart, deletes deliveries older than 30 days. New events are sent straight away without it. |
| `WEBHOOKS_ENABLED` (env) | `true` | `false` stops noticing events for outbound webhooks altogether (nothing new is queued). |
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints use http and private or local addresses — for local testing only (the e2e tests set it). |
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints and linked products use http and private or local addresses — for local testing only (the e2e tests set it). |
| `FEED_JOBS_ENABLED` (env) | `true` | The `feed` job (every 5 minutes: publishes what changed in the event feed, e.g. an event going live or selling out, and tells linked products) and `feed-sync` (every 15 minutes: fetches events from the linked products shown here). Off: the feed is still rebuilt when it's asked for. |
| `feed_publish` | `true` | Settings → Linked products → **Publish my events**: the public event feed (`/api/feed/v1/events`) for the church's other products. |
| `SERIES_JOBS_ENABLED` (env) | `true` | The `series` job (every 15 minutes) that emails a series' followers once when a new event in it goes live (News & announcements: only people opted in to news). |
| `RETENTION_JOBS_ENABLED` (env) | `true` | The nightly 03:30 `retention` job. Off means nothing expires automatically. |
| `wawp_webhook_last_seen` | — | Set when WAWP's webhook arrives with the right secret; the readiness page uses it to check WhatsApp STOP is set up. |
+3 -1
View File
@@ -80,8 +80,10 @@ VOLUNTEER_JOBS_ENABLED=true
SERIES_JOBS_ENABLED=true
WEBHOOKS_JOBS_ENABLED=true
WEBHOOKS_ENABLED=true
# Local testing only: lets webhook endpoints be http:// or on a private network
# Local testing only: lets webhook endpoints and linked products be http:// or on a private network
WEBHOOKS_ALLOW_PRIVATE=false
# Linked products (2.4.0): publish the event feed every 5 minutes, fetch linked products' events every 15
FEED_JOBS_ENABLED=true
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
PRIVACY_JOBS_ENABLED=true
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
+1
View File
@@ -22,6 +22,7 @@
},
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
"@crosscode/contracts": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
@@ -0,0 +1,54 @@
-- 2.4.0: linked products and the event feed (docs/EVENTS-2.4-PLAN.md).
ALTER TYPE "AdminAuditAction" ADD VALUE 'product_link_connected';
ALTER TYPE "AdminAuditAction" ADD VALUE 'product_link_disconnected';
ALTER TYPE "AdminAuditAction" ADD VALUE 'feed_publish_toggled';
ALTER TYPE "AdminAuditAction" ADD VALUE 'feed_show_toggled';
CREATE TABLE "ProductLink" (
"installId" TEXT NOT NULL,
"product" TEXT NOT NULL,
"url" TEXT NOT NULL,
"publicKey" TEXT NOT NULL,
"secret" TEXT NOT NULL,
"connectedAt" TIMESTAMP(3) NOT NULL,
"connectedById" TEXT,
"showEvents" BOOLEAN NOT NULL DEFAULT false,
"lastSyncAt" TIMESTAMP(3),
"lastSyncError" TEXT,
"lastGoodAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
);
CREATE TABLE "LinkNonce" (
"nonce" TEXT NOT NULL,
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
);
CREATE INDEX "LinkNonce_seenAt_idx" ON "LinkNonce"("seenAt");
CREATE TABLE "FeedEntry" (
"eventId" TEXT NOT NULL,
"hash" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"changedAt" TIMESTAMP(3) NOT NULL,
"removedAt" TIMESTAMP(3),
CONSTRAINT "FeedEntry_pkey" PRIMARY KEY ("eventId")
);
CREATE INDEX "FeedEntry_changedAt_idx" ON "FeedEntry"("changedAt");
CREATE INDEX "FeedEntry_removedAt_idx" ON "FeedEntry"("removedAt");
CREATE TABLE "ImportedEvent" (
"key" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3) NOT NULL,
"campusSlug" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("key")
);
CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId");
CREATE INDEX "ImportedEvent_endsAt_idx" ON "ImportedEvent"("endsAt");
ALTER TABLE "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
+65
View File
@@ -847,6 +847,10 @@ enum AdminAuditAction {
webhook_endpoint_changed
registrations_bulk
ai_settings_changed
product_link_connected
product_link_disconnected
feed_publish_toggled
feed_show_toggled
}
// Append-only audit trail for admin/supervisor-initiated actions with money or
@@ -2377,3 +2381,64 @@ model RecoveryCode {
@@index([userId])
}
// ─── Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md) ─────────────────────
// A link to one of the church's other products (Settings → Linked products → Connect): the
// shared secret signs the calls between the two (the event.changed webhook). The sibling's key
// is the one the Hub listed when it was connected.
model ProductLink {
installId String @id // the sibling's Hub install id
product String // website | app | accounts
url String
publicKey String
secret String // encrypted (utils/encryption)
connectedAt DateTime
connectedById String? // a user here; null when the sibling connected
// "Show events from this product" (off by default).
showEvents Boolean @default(false)
lastSyncAt DateTime?
lastSyncError String?
lastGoodAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
importedEvents ImportedEvent[]
}
// Nonces of link messages already accepted (crosscode.link/1), so one can't be replayed. Kept
// an hour: a message older than five minutes is refused anyway.
model LinkNonce {
nonce String @id
seenAt DateTime @default(now())
@@index([seenAt])
}
// What the feed last published for each event (feed/entries.ts): changedAt moves only when what
// a sibling sees changes, so ?updatedSince= also catches going live, closing and selling out.
model FeedEntry {
eventId String @id
hash String
payload Json
changedAt DateTime
removedAt DateTime? // stopped being public: listed in `deleted`
@@index([changedAt])
@@index([removedAt])
}
// An event from a linked product's feed: a read-only copy, never published again.
model ImportedEvent {
key String @id // eventKey(): "<product>:<id>"
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
payload Json // the crosscode.event/1 as received
startsAt DateTime
endsAt DateTime
campusSlug String?
updatedAt DateTime
@@index([linkId])
@@index([endsAt])
}
+3
View File
@@ -135,6 +135,9 @@ const webhookRoutes = require('./routes/webhookRoutes');
// Mount webhook routes BEFORE JSON body parser to avoid double-reading the stream
app.use('/api/webhooks', webhookRoutes);
app.use('/api/v2/webhooks', webhooksRouter);
// The church's other products (2.4.0): the event feed, event.changed and Connect
// (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook).
app.use('/api', require('./links/routes').crossProductRouter());
// Apply JSON body parser for all non-webhook routes
app.use(express.json());
+26 -1
View File
@@ -87,8 +87,33 @@ function withWebhooks(base) {
});
}
/**
* The event feed (2.4.0, src/feed/entries.ts): a write to anything a linked product would see
* (an event, its tickets, sessions, series or campus, or a registration that can fill it up)
* refreshes the feed a few seconds later. Only starts a timer; never affects the write.
*/
const FEED_MODELS = new Set(['Event', 'EventOption', 'OptionVariant', 'EarlyBirdTier', 'EventSession', 'EventSeries', 'Campus', 'Registration', 'RegistrationOption', 'WaitlistEntry']);
const WRITES = new Set(['create', 'createMany', 'createManyAndReturn', 'update', 'updateMany', 'updateManyAndReturn', 'upsert', 'delete', 'deleteMany']);
function withFeed(client) {
const touched = () => {
try { require('../feed/entries').changedSoon(); } catch (e) { console.warn('[feed] changedSoon:', e?.message || e); }
};
return client.$extends({
query: {
$allModels: {
async $allOperations({ model, operation, args, query }) {
const result = await query(args);
if (FEED_MODELS.has(model) && WRITES.has(operation)) touched();
return result;
},
},
},
});
}
function createPrismaClient() {
return withWebhooks(createBaseClient());
return withFeed(withWebhooks(createBaseClient()));
}
const prisma = createPrismaClient();
+244
View File
@@ -0,0 +1,244 @@
/**
* An event as `crosscode.event/1` (docs/EVENTS-2.4-PLAN.md §3): what the feed publishes and what
* the event page's JSON-LD is built from (@crosscode/seo).
*
* `buildCrosscodeEvent` is pure (the event, what's left of each ticket and the site's details in,
* the payload out) so it can be tested without a database; `loadForFeed` reads what it needs.
*
* Never in here: the event's contact person, kids check-in and volunteer tickets, staff prices,
* the attendee form. Only what the public event page already shows.
*/
import type { CrosscodeEvent } from '@crosscode/contracts';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS utils */
const sessionsUtil = require('../utils/sessions') as {
activeSessions<S extends { cancelledAt?: Date | string | null; startsAt: Date | string }>(sessions: S[]): S[];
registrationClosesAt(event: object, sessions: object[]): Date;
isPickOption(event: object, option: object): boolean;
};
const { publicOptions } = require('../utils/volunteers') as { publicOptions<O>(event: object): O[] };
const { getEffectiveUnitPrice } = require('../utils/pricing') as { getEffectiveUnitPrice(option: object, ref: Date | null, at: Date): number };
/* eslint-enable @typescript-eslint/no-require-imports */
export type FeedContext = {
/** This install's Hub id (origin.installId). */
installId: string;
/** The site's address, without a trailing slash. */
baseUrl: string;
timezone: string;
/** Campuses switched on (otherwise every event is for the whole church). */
campusesOn: boolean;
now: Date;
};
export type FeedOption = {
id: string;
price: number;
isMainTicket: boolean;
stockLimit: number;
sessionMode?: string;
earlyBirdTiers?: { deadline: Date | string; price: number; order?: number | null }[];
variants?: { price: number | null }[];
};
export type FeedEventRow = {
id: string;
title: string;
description: string | null;
startDate: Date;
endDate: Date;
goLiveAt: Date | null;
registrationDeadline: Date | null;
picture: string | null;
location: string | null;
requiresRegistration: boolean;
waitlistEnabled: boolean;
scheduleType: string;
attendanceMode: string;
lateJoinEnabled: boolean;
lateJoinUntilSessionId: string | null;
kidsOptionId?: string | null;
volunteerOptionId?: string | null;
campus: { slug: string; name: string } | null;
series: { id: string; name: string } | null;
sessions: { id: string; label: string | null; startsAt: Date; endsAt: Date; location: string | null; cancelledAt: Date | null }[];
eventOptions: FeedOption[];
};
/** Places left per option (`null` = no limit). Missing options count as unlimited. */
export type Availability = Map<string, number | null>;
export type BuiltEvent = {
event: CrosscodeEvent;
/** The event's own lowest and highest current prices, for its JSON-LD (`null` when free). */
priceRangeCents: { lowCents: number; highCents: number } | null;
};
const cut = (s: string | null | undefined, max: number): string | null => {
const t = String(s ?? '').trim();
return t ? (t.length > max ? `${t.slice(0, max - 1)}…` : t) : null;
};
/** "/uploads/…" (as stored) → an absolute address on the site, served under /api (2.2.0). */
export function absolute(baseUrl: string, raw: string | null | undefined): string | null {
const v = String(raw ?? '').trim();
if (!v) return null;
if (/^https?:\/\//i.test(v)) return v;
const path = v.startsWith('/') ? v : `/${v}`;
return `${baseUrl}${/^\/uploads\//.test(path) ? `/api${path}` : path}`;
}
/**
* Plain text as markdown that reads the same: markdown characters escaped, line breaks kept
* (Events descriptions are plain text shown with their line breaks).
*/
export function plainToMarkdown(text: string | null | undefined): string | null {
const t = String(text ?? '').replace(/\r\n?/g, '\n').trim();
if (!t) return null;
const lines = t.split('\n').map((line) => line
.replace(/[\\`*_[\]<>|~]/g, (c) => `\\${c}`)
// A line that would start a heading, a list, a quote or a numbered list.
.replace(/^(\s*)([#>+-])/, '$1\\$2')
.replace(/^(\s*\d+)([.)])(\s)/, '$1\\$2$3'));
// A hard break between lines of the same paragraph (two spaces), blank lines stay paragraphs.
return lines.map((l, i) => (i < lines.length - 1 && l.trim() && lines[i + 1]!.trim() ? `${l} ` : l)).join('\n').slice(0, 20000);
}
/** Today's price of each ticket (early-bird when one is open, else each variant's or the base price), in rand. */
function currentPrices(options: FeedOption[], now: Date): number[] {
const prices: number[] = [];
for (const o of options) {
if (o.variants && o.variants.length > 0) {
for (const v of o.variants) prices.push(v.price ?? o.price);
continue;
}
prices.push(getEffectiveUnitPrice(o, null, now));
}
return prices.filter((p) => Number.isFinite(p) && p >= 0);
}
function registration(row: FeedEventRow, options: FeedOption[], available: Availability, ctx: FeedContext, pageUrl: string): CrosscodeEvent['registration'] {
const closes = sessionsUtil.registrationClosesAt(row, row.sessions);
const closesAt = closes && Number.isFinite(closes.getTime()) ? closes.toISOString() : null;
if (!row.requiresRegistration) {
// Contact-only events: no tickets; the description says how to take part.
return { mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null };
}
const main = options.filter((o) => o.isMainTicket);
const priced = main.length > 0 ? main : options;
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
const low = prices.length > 0 ? Math.min(...prices) : 0;
let status: CrosscodeEvent['registration']['status'] = 'open';
if (row.goLiveAt && ctx.now < row.goLiveAt) status = 'not_open';
else if (closesAt && ctx.now >= new Date(closesAt)) status = 'closed';
else if (main.length > 0 && main.every((o) => o.stockLimit > 0 && (available.get(o.id) ?? 1) <= 0)) status = row.waitlistEnabled ? 'waitlist' : 'full';
return {
mode: 'origin',
url: pageUrl,
status,
opensAt: row.goLiveAt && ctx.now < row.goLiveAt ? row.goLiveAt.toISOString() : null,
closesAt,
priceFrom: low > 0 ? { amountCents: low, currency: 'ZAR' } : null,
};
}
export function buildCrosscodeEvent(row: FeedEventRow, available: Availability, ctx: FeedContext): BuiltEvent {
const pageUrl = `${ctx.baseUrl}/events/${row.id}`;
const options = publicOptions<FeedOption>(row);
const live = sessionsUtil.activeSessions(row.sessions);
const multi = row.scheduleType === 'sessions' && row.sessions.length > 0;
// startsAt / endsAt are the first start and last end of the sessions that still run.
const startsAt = multi && live.length > 0 ? live[0]!.startsAt : row.startDate;
const endsAt = multi && live.length > 0 ? live.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), live[0]!.endsAt) : row.endDate;
const place = cut(row.location, 200);
const online = place && /^https?:\/\//i.test(place) ? place : null;
const reg = registration(row, options, available, ctx, pageUrl);
const priced = options.filter((o) => o.isMainTicket).length > 0 ? options.filter((o) => o.isMainTicket) : options;
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
const priceRangeCents = row.requiresRegistration && prices.some((p) => p > 0) ? { lowCents: Math.min(...prices), highCents: Math.max(...prices) } : null;
const event: CrosscodeEvent = {
schema: 'crosscode.event/1',
id: row.id,
origin: { product: 'events', installId: ctx.installId, url: pageUrl },
status: 'published',
// The feed puts the time it last changed here (feed/entries.ts).
updatedAt: ctx.now.toISOString(),
title: cut(row.title, 200) ?? 'Event',
summary: null,
description: plainToMarkdown(row.description),
imageUrl: absolute(ctx.baseUrl, row.picture),
timezone: ctx.timezone,
startsAt: new Date(startsAt).toISOString(),
endsAt: new Date(endsAt).toISOString(),
allDay: false,
sessions: multi
? [...row.sessions]
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime())
.slice(0, 500)
.map((s) => ({
id: s.id,
label: cut(s.label, 200),
startsAt: new Date(s.startsAt).toISOString(),
endsAt: new Date(s.endsAt).toISOString(),
location: cut(s.location, 300),
cancelled: !!s.cancelledAt,
}))
: [],
location: place ? (online ? { name: null, address: null, onlineUrl: online } : { name: place, address: null, onlineUrl: null }) : null,
campus: ctx.campusesOn && row.campus ? { slug: row.campus.slug, name: cut(row.campus.name, 200) ?? row.campus.slug } : null,
series: row.series ? { id: row.series.id, name: cut(row.series.name, 200) ?? 'Series' } : null,
tags: [],
registration: reg,
};
return { event, priceRangeCents };
}
/** What `loadForFeed` selects (and the e2e/unit fixtures build). */
export const FEED_EVENT_SELECT = {
id: true, title: true, description: true, startDate: true, endDate: true, goLiveAt: true, registrationDeadline: true,
picture: true, location: true, requiresRegistration: true, waitlistEnabled: true, scheduleType: true, attendanceMode: true,
lateJoinEnabled: true, lateJoinUntilSessionId: true, kidsOptionId: true, volunteerOptionId: true, updatedAt: true,
campus: { select: { slug: true, name: true } },
series: { select: { id: true, name: true } },
sessions: { select: { id: true, label: true, startsAt: true, endsAt: true, location: true, cancelledAt: true } },
eventOptions: { select: { id: true, price: true, isMainTicket: true, stockLimit: true, sessionMode: true, earlyBirdTiers: true, variants: { select: { price: true } } } },
} as const;
/**
* Places left on each limited main ticket. "Pick sessions" tickets have places per session; they
* count as sold out only when every session that still runs is.
*/
export async function availabilityFor(row: FeedEventRow): Promise<Availability> {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { takenCount } = require('../utils/stock') as { takenCount(where: object): Promise<number> };
const out: Availability = new Map();
for (const o of publicOptions<FeedOption>(row)) {
if (!o.isMainTicket || !(o.stockLimit > 0)) continue;
if (sessionsUtil.isPickOption(row, o)) {
let left = 0;
for (const s of sessionsUtil.activeSessions(row.sessions)) left += Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id, sessionId: s.id }));
out.set(o.id, left);
} else {
out.set(o.id, Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id })));
}
}
return out;
}
/**
* One event as `crosscode.event/1`, for its own page's JSON-LD (whether or not it's public: a
* hidden event's page is reachable by its link). `null` when there's no such event.
*/
export async function crosscodeEventFor(eventId: string, now = new Date()): Promise<BuiltEvent | null> {
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { feedContext } = require('./context') as typeof import('./context');
/* eslint-enable @typescript-eslint/no-require-imports */
const row = (await prisma.event.findUnique({ where: { id: eventId }, select: FEED_EVENT_SELECT })) as FeedEventRow | null;
if (!row) return null;
return buildCrosscodeEvent(row, await availabilityFor(row), await feedContext(now));
}
+44
View File
@@ -0,0 +1,44 @@
/**
* What every part of the feed and of Linked products needs to know about this site: its Hub id,
* its address, its timezone and whether campuses and publishing are on.
*/
import type { FeedContext } from './build';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { getSetting } = require('../utils/settingsCache') as { getSetting(key: string, fallback?: string): Promise<string> };
const { campusesEnabled } = require('../utils/campuses') as { campusesEnabled(): Promise<boolean> };
/* eslint-enable @typescript-eslint/no-require-imports */
/** Setting: "Publish my events" (on unless set to "false"). */
export const PUBLISH_KEY = 'feed_publish';
export async function publishOn(): Promise<boolean> {
return String(await getSetting(PUBLISH_KEY, 'true')).toLowerCase() !== 'false';
}
/** The site's address, as it tells the Hub (hub/report.js installInfo). */
export async function siteUrl(): Promise<string> {
const url = await getSetting('app_base_url', process.env.FRONTEND_URL || '');
return String(url || process.env.FRONTEND_URL || '').split(',')[0]!.trim().replace(/\/+$/, '');
}
export async function hubInstallId(): Promise<string | null> {
const row = await prisma.appSetting.findUnique({ where: { key: 'hub_install_id' } });
return row?.value || null;
}
/** Placeholder id for a site not connected to the Hub (its JSON-LD still works; it has no feed). */
export const NO_INSTALL_ID = '00000000-0000-4000-8000-000000000000';
export async function feedContext(now = new Date()): Promise<FeedContext & { connected: boolean }> {
const [installId, baseUrl, campusesOn] = await Promise.all([hubInstallId(), siteUrl(), campusesEnabled().catch(() => false)]);
return {
installId: installId || NO_INSTALL_ID,
connected: !!installId,
baseUrl,
timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg',
campusesOn,
now,
};
}
+139
View File
@@ -0,0 +1,139 @@
/**
* The published feed (docs/EVENTS-2.4-PLAN.md §3): `FeedEntry` holds what was last published for
* each event, so `?updatedSince=` is right even when an event changes without its row changing
* (it goes live, registration closes, it sells out) and when it stops being public (Events never
* deletes an event, it deactivates it).
*
* `refreshFeed` builds every event that is public and ended at most 30 days ago, and moves an
* entry's `changedAt` only when its payload changed. Run by the `feed` job (every 5 minutes),
* shortly after any change to events, tickets or registrations (`changedSoon`), and before the
* feed is served when the last run is more than a minute old.
*/
import crypto from 'crypto';
import { canonicalJson, eventSchema, EVENT_FEED_SCHEMA, type CrosscodeEvent, type EventFeed } from '@crosscode/contracts';
import { availabilityFor, buildCrosscodeEvent, FEED_EVENT_SELECT, type FeedEventRow } from './build';
import { feedContext } from './context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { publicEventWhere } = require('../utils/series') as { publicEventWhere(now: Date): object };
/* eslint-enable @typescript-eslint/no-require-imports */
const DAY = 24 * 60 * 60 * 1000;
/** Ended events stay in a full fetch this long. */
export const ENDED_KEEP_DAYS = 30;
/** Entries of events that stopped being public are kept (as `deleted`) this long. */
export const REMOVED_KEEP_DAYS = 90;
/** The hash of what a sibling sees (without `updatedAt`, which is the entry's `changedAt`). */
export function payloadHash(event: CrosscodeEvent): string {
const { updatedAt: _ignored, ...rest } = event;
return crypto.createHash('sha256').update(canonicalJson(rest)).digest('hex');
}
export type RefreshResult = { changed: string[]; removed: string[]; skipped: { id: string; reason: string }[] };
let lastRefreshAt = 0;
let running: Promise<RefreshResult> | null = null;
export async function refreshFeed(now = new Date(), db = prisma): Promise<RefreshResult> {
const ctx = await feedContext(now);
const result: RefreshResult = { changed: [], removed: [], skipped: [] };
// Without a Hub install id there's no origin to publish under.
if (!ctx.connected) return result;
const rows = (await db.event.findMany({
where: { AND: [publicEventWhere(now), { endDate: { gte: new Date(now.getTime() - ENDED_KEEP_DAYS * DAY) } }] },
select: FEED_EVENT_SELECT,
})) as FeedEventRow[];
const entries: { eventId: string; hash: string; removedAt: Date | null }[] = await db.feedEntry.findMany({ select: { eventId: true, hash: true, removedAt: true } });
const byId = new Map(entries.map((e) => [e.eventId, e]));
const current = new Set<string>();
for (const row of rows) {
const built = buildCrosscodeEvent(row, await availabilityFor(row), ctx);
const check = eventSchema.safeParse(built.event);
if (!check.success) {
// Never publish something the contract refuses; the next change may fix it.
result.skipped.push({ id: row.id, reason: check.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ') });
continue;
}
current.add(row.id);
const hash = payloadHash(built.event);
const prev = byId.get(row.id);
if (prev && prev.hash === hash && !prev.removedAt) continue;
await db.feedEntry.upsert({
where: { eventId: row.id },
create: { eventId: row.id, hash, payload: built.event, changedAt: now, removedAt: null },
update: { hash, payload: built.event, changedAt: now, removedAt: null },
});
result.changed.push(row.id);
}
// Entries no longer built: an event that stopped being public goes into `deleted`; one that
// only ended long enough ago drops out quietly (siblings keep their copy).
const gone = entries.filter((e) => !e.removedAt && !current.has(e.eventId)).map((e) => e.eventId);
if (gone.length > 0) {
const stillPublic = new Set<string>(
(await db.event.findMany({ where: { AND: [{ id: { in: gone } }, publicEventWhere(now)] }, select: { id: true } })).map((e: { id: string }) => e.id),
);
const skipped = new Set(result.skipped.map((s) => s.id));
for (const id of gone) {
if (skipped.has(id)) continue;
if (stillPublic.has(id)) await db.feedEntry.delete({ where: { eventId: id } });
else {
await db.feedEntry.update({ where: { eventId: id }, data: { removedAt: now } });
result.removed.push(id);
}
}
}
await db.feedEntry.deleteMany({ where: { removedAt: { lt: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY) } } });
// Wall-clock time of the run (not `now`, which tests and catch-up runs may set).
lastRefreshAt = Date.now();
return result;
}
/** One refresh at a time in this process; the job, `changedSoon` and the feed share it. */
export function refreshOnce(now = new Date()): Promise<RefreshResult> {
if (!running) running = refreshFeed(now).finally(() => { running = null; });
return running;
}
export function lastRefresh(): number {
return lastRefreshAt;
}
/** The feed answer (`crosscode.event-feed/1`). */
export async function feedResponse(updatedSince: Date | null, now = new Date(), db = prisma): Promise<EventFeed> {
const live = await db.feedEntry.findMany({
where: { removedAt: null, ...(updatedSince ? { changedAt: { gt: updatedSince } } : {}) },
orderBy: { changedAt: 'asc' },
});
const deleted = updatedSince
? await db.feedEntry.findMany({ where: { removedAt: { gt: updatedSince } }, orderBy: { removedAt: 'asc' }, select: { eventId: true, removedAt: true } })
: [];
return {
schema: EVENT_FEED_SCHEMA,
generatedAt: now.toISOString(),
events: live.map((e: { payload: CrosscodeEvent; changedAt: Date }) => ({ ...e.payload, updatedAt: e.changedAt.toISOString() })),
deleted: deleted.map((d: { eventId: string; removedAt: Date }) => ({ id: d.eventId, deletedAt: d.removedAt.toISOString() })),
};
}
// ─── After a change ────────────────────────────────────────────────────────────
let timer: NodeJS.Timeout | null = null;
/**
* Something that can change the feed was written (config/db.js): refresh a few seconds later
* (one refresh for a burst of writes) and tell connected siblings. Never throws.
*/
export function changedSoon(delayMs = 5000): void {
if (timer) return;
timer = setTimeout(() => {
timer = null;
// eslint-disable-next-line @typescript-eslint/no-require-imports
(require('./notify') as typeof import('./notify')).refreshAndNotify().catch((e: unknown) => console.warn('[feed] refresh failed:', (e as Error)?.message || e));
}, delayMs);
timer.unref?.();
}
+56
View File
@@ -0,0 +1,56 @@
/**
* Telling connected siblings the feed changed (`event.changed`, signed with each link's secret),
* so they fetch straight away instead of at their next 15-minute poll. One try, and one more a
* minute later; after that the poll catches up, so a sibling that's down misses nothing.
*/
import { EVENT_FEED_SCHEMA, FEED_PATHS, type EventChanged } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { hubInstallId, publishOn } from './context';
import { refreshOnce, type RefreshResult } from './entries';
import { callSibling, siblingUrl } from '../links/http';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
const RETRY_MS = 60 * 1000;
type LinkRow = { installId: string; url: string; secret: string };
export async function sendChanged(link: LinkRow, eventIds: string[], senderId: string, now = new Date()): Promise<void> {
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: now.toISOString(), eventIds: eventIds.slice(0, 100) };
const raw = JSON.stringify(body);
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: decrypt(link.secret), rawBody: raw });
await callSibling(await siblingUrl(link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
}
/** Tells every connected sibling; failures are retried once, then left to the sibling's poll. */
export async function notifyLinks(eventIds: string[]): Promise<{ told: number; failed: number }> {
if (eventIds.length === 0 || !(await publishOn())) return { told: 0, failed: 0 };
const senderId = await hubInstallId();
if (!senderId) return { told: 0, failed: 0 };
const links: LinkRow[] = await prisma.productLink.findMany({ select: { installId: true, url: true, secret: true } });
let told = 0;
let failed = 0;
await Promise.all(links.map(async (link) => {
try {
await sendChanged(link, eventIds, senderId);
told++;
} catch (e) {
failed++;
console.warn(`[feed] event.changed to ${link.url} failed, trying once more in a minute:`, (e as Error)?.message || e);
setTimeout(() => {
sendChanged(link, eventIds, senderId).catch((err) => console.warn(`[feed] event.changed to ${link.url} failed again (its poll will catch up):`, (err as Error)?.message || err));
}, RETRY_MS).unref?.();
}
}));
return { told, failed };
}
/** The `feed` job: refresh what's published and tell siblings what changed. */
export async function refreshAndNotify(now = new Date()): Promise<RefreshResult & { told: number }> {
const result = await refreshOnce(now);
const { told } = await notifyLinks([...result.changed, ...result.removed]);
return { ...result, told };
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Showing events from linked products (docs/EVENTS-2.4-PLAN.md §4): each link with "Show events
* from this product" on is fetched every 15 minutes (`feed-sync` job) and straight away on a
* valid `event.changed` (`feed-sync-link` task). Its events are kept as read-only copies
* (`ImportedEvent`), keyed by origin product + id, and never published again.
*
* - The last good copy stays: a failed fetch only records the error.
* - One bad event is skipped and logged (parseEventFeed); it never holds up the rest.
* - Only events that really come from that sibling are taken (origin.installId and product
* must match the link), so one product can't put words in another's mouth.
*/
import { eventKey, FEED_PATHS, parseEventFeed, type CrosscodeEvent } from '@crosscode/contracts';
import { callSibling, siblingUrl } from '../links/http';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
const OVERLAP_MS = 5 * 60 * 1000;
type Link = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
export async function syncLink(link: Link, now = new Date()): Promise<SyncResult> {
if (!link.showEvents) return { installId: link.installId, ok: true, imported: 0, deleted: 0 };
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(link.url, FEED_PATHS.events, since ? { updatedSince: since.toISOString() } : {});
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1: ${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`);
const { feed, rejected } = parsed;
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`}):`, r.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; '));
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
const skipped = feed.events.length - theirs.length;
for (const e of theirs) await upsert(link.installId, e);
const deletedKeys = feed.deleted.map((d) => `${link.product}:${d.id}`);
let deleted = deletedKeys.length ? (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { in: deletedKeys } } })).count : 0;
// A full fetch is the whole list: anything not in it is gone (or ended a while ago).
if (!since) deleted += (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { notIn: theirs.map(eventKey) } } })).count;
await prisma.productLink.update({
where: { installId: link.installId },
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
});
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length, skipped };
} catch (e) {
const error = String((e as Error)?.message || e).slice(0, 500);
await prisma.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
return { installId: link.installId, ok: false, error };
}
}
async function upsert(linkId: string, e: CrosscodeEvent) {
const data = { linkId, payload: e, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), campusSlug: e.campus?.slug ?? null, updatedAt: new Date(e.updatedAt) };
await prisma.importedEvent.upsert({ where: { key: eventKey(e) }, create: { key: eventKey(e), ...data }, update: data });
}
/** The `feed-sync` job: every link that shows events, one after another (one failing never stops the rest). */
export async function syncAll(now = new Date()): Promise<{ links: number; failed: number }> {
const links: Link[] = await prisma.productLink.findMany({ where: { showEvents: true } });
let failed = 0;
for (const link of links) if (!(await syncLink(link, now)).ok) failed++;
return { links: links.length, failed };
}
/** The `feed-sync-link` task (after an `event.changed`). */
export async function syncOne(installId: string): Promise<SyncResult | { skipped: string }> {
const link: Link | null = await prisma.productLink.findUnique({ where: { installId } });
if (!link) return { skipped: 'no such link' };
return syncLink(link);
}
+129 -8
View File
@@ -6,8 +6,18 @@
* hub_last_heartbeat_at, hub_last_error, hub_latest_version,
* hub_releases, hub_notices (JSON from the last heartbeat: what's new, provider's notices),
* hub_update_requested_at, hub_update_requested_version,
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub).
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub),
* hub_v1_until (the Hub refused protocol v2: speak v1 until then; 2.4.0),
* and this site's key pair and the Hub's list of the church's other products (links/store.ts).
* These keys are kept out of the generic settings endpoints (settingsController).
*
* Protocol (2.4.0, docs/EVENTS-2.4-PLAN.md §1): register and heartbeat speak **v2**
* (`product: "events"`, this site's public key, the church's other products in the reply). An
* install that registered with v1 moves over by sending its key on the heartbeat (Hub 2.2.0
* saves it), so nobody needs the licence key again. If the Hub refuses a v2 body (a Hub before
* 2.0, or a body the Hub's contract doesn't accept), the same heartbeat goes again as v1 and v1
* is used for a day: the licence must keep refreshing whatever happens. Update requests and AI
* calls stay v1, which every Hub accepts.
*/
const crypto = require('crypto');
@@ -15,10 +25,16 @@ const prisma = require('../config/db');
const { encrypt, decrypt } = require('../utils/encryption');
const { verifyToken, clearLicenceCache } = require('./licence');
const report = require('./report');
const { hub } = require('@crosscode/contracts');
const store = require('../links/store');
/** Update requests and AI calls (as in v1; the Hub answers both versions). */
const PROTOCOL_VERSION = 1;
/** Register and heartbeat (2.4.0). */
const HEARTBEAT_PROTOCOL = 2;
const V1_FALLBACK_MS = 24 * 60 * 60 * 1000;
const TIMEOUT_MS = 15000;
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version'];
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version', 'hub_v1_until', ...store.KEY_SETTINGS];
function hubUrl() {
return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, '');
@@ -100,11 +116,26 @@ async function connect(licenceKey, adminContact) {
if (!/^https?:\/\//.test(install.url)) {
throw new HubError('Set the site\'s web address first (FRONTEND_URL on the server, or Site settings → Organisation).', 'NO_SITE_URL', 400);
}
const data = await post('/api/installs/register', {
const v1Body = {
protocolVersion: PROTOCOL_VERSION,
licenceKey: String(licenceKey || '').trim(),
install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null },
});
};
// v2 (2.4.0): the product and this site's public key, so the church's other products can link.
// Anything wrong with the key (or a Hub that only speaks v1) registers with v1 instead.
const publicKeyPem = await ownPublicKey();
const v2Body = { ...v1Body, protocolVersion: HEARTBEAT_PROTOCOL, licenceKey: v1Body.licenceKey.toUpperCase(), product: 'events', install: { ...v1Body.install, publicKey: publicKeyPem } };
const v2 = !!publicKeyPem && !(await v1Only()) && hub.registerRequestSchema.safeParse(v2Body).success;
let data;
let sentV2 = v2;
try {
data = await post('/api/installs/register', v2 ? v2Body : v1Body);
} catch (e) {
if (!v2 || !refusedV2(e)) throw e;
await useV1ForADay();
sentV2 = false;
data = await post('/api/installs/register', v1Body);
}
const claims = verifyToken(data.licence);
if (!claims || claims.installId !== data.installId) {
throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL pointing at the right Hub?', 'BAD_LICENCE', 502);
@@ -118,16 +149,106 @@ async function connect(licenceKey, adminContact) {
hub_latest_version: data.latestVersion || null,
...fromHub(data),
});
if (sentV2) {
try {
await store.saveLinkedProducts(data.linkedProducts);
// Registered with the key, so the Hub has it.
await store.setPublicKeyStatus('matches');
} catch (e) {
console.warn('[hub] Could not save the linked products:', e?.message || e);
}
}
return claims;
}
/** This site's public key, or null when it can't be made or read (then v1 is used). */
async function ownPublicKey() {
try {
return (await store.keyPair()).publicKeyPem;
} catch (e) {
console.warn('[hub] No key pair for protocol v2, using v1:', e?.message || e);
return null;
}
}
/** Whether the Hub refused a v2 body (too old for v2, or a contract it doesn't accept): retry as v1. */
function refusedV2(e) {
return e instanceof HubError && e.statusCode === 400 && ['UNSUPPORTED_PROTOCOL', 'INVALID_REQUEST'].includes(e.code);
}
async function v1Only() {
const until = (await read(['hub_v1_until'])).hub_v1_until;
return !!until && new Date(until).getTime() > Date.now();
}
async function useV1ForADay() {
await save({ hub_v1_until: new Date(Date.now() + V1_FALLBACK_MS).toISOString() });
}
/**
* The health as protocol v2 wants it: every field there (a part that couldn't be read is
* reported as nothing wrong rather than left out).
*/
function v2Health(h) {
return {
...h,
jobs: h.jobs || { mode: 'unknown', failedLast24h: 0 },
pendingMigrations: Number.isInteger(h.pendingMigrations) ? h.pendingMigrations : 0,
};
}
/**
* The heartbeat body: v2 when it fits the contract (with the public key until the Hub has it),
* otherwise v1. Returns { body, v2 }.
*/
async function heartbeatBody() {
const health = await report.health();
const stats = await report.stats();
const v1 = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health, stats };
if (await v1Only()) return { body: v1, v2: false };
const publicKeyPem = await ownPublicKey();
if (!publicKeyPem) return { body: v1, v2: false };
const status = await store.publicKeyStatus().catch(() => null);
const v2 = {
protocolVersion: HEARTBEAT_PROTOCOL,
product: 'events',
version: report.APP_VERSION,
health: v2Health(health),
stats,
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
};
const check = hub.heartbeatRequestSchema.safeParse(v2);
if (!check.success) {
console.warn('[hub] The v2 heartbeat doesn\'t fit the contract, sending v1:', check.error.issues.slice(0, 3).map(i => `${i.path.join('.')} ${i.message}`).join('; '));
return { body: v1, v2: false };
}
return { body: v2, v2: true };
}
/** Send a heartbeat (the `hub-heartbeat` job). Skips quietly when not connected. */
async function heartbeat() {
const s = await read(['hub_install_id', 'hub_install_secret']);
if (!s.hub_install_id || !s.hub_install_secret) return { skipped: 'not connected' };
const body = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health: await report.health(), stats: await report.stats() };
let { body, v2 } = await heartbeatBody();
try {
const data = await signedPost('/api/installs/heartbeat', body);
let data;
try {
data = await signedPost('/api/installs/heartbeat', body);
} catch (e) {
if (!v2 || !refusedV2(e)) throw e;
console.warn(`[hub] The Hub refused a v2 heartbeat (${e.code}: ${e.message}); using v1 for a day.`);
await useV1ForADay();
({ body, v2 } = await heartbeatBody());
data = await signedPost('/api/installs/heartbeat', body);
}
if (v2) {
try {
await store.saveLinkedProducts(data.linkedProducts);
if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus);
} catch (e) {
console.warn('[hub] Could not save the linked products:', e?.message || e);
}
}
const claims = verifyToken(data.licence);
await save({
// Keep the old token if the new one doesn't check out (never accept an unverified one).
@@ -137,7 +258,7 @@ async function heartbeat() {
hub_latest_version: data.latestVersion || null,
...fromHub(data),
});
return { ok: true, status: claims?.status || null };
return { ok: true, status: claims?.status || null, protocol: v2 ? 2 : 1 };
} catch (e) {
await save({ hub_last_error: `${new Date().toISOString()} ${e.code || ''} ${e.message}`.slice(0, 500) });
// The Hub doesn't know this install any more (licence released): drop the connection and the
@@ -245,4 +366,4 @@ async function connectFromEnv({ attempts = 5, delayMs = 60 * 1000, sleep = ms =>
return { connected: false, reason: 'unreachable' };
}
module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
module.exports = { PROTOCOL_VERSION, HEARTBEAT_PROTOCOL, HUB_KEYS, heartbeatBody, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
+10
View File
@@ -75,6 +75,14 @@ const JOBS = [
name: 'hub-heartbeat', label: 'Cross Events Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED',
run: () => require('../hub/client').heartbeat(),
},
{
name: 'feed', label: 'Event feed: publish changes (going live, closing, selling out) and tell linked products', cron: '*/5 * * * *', env: 'FEED_JOBS_ENABLED',
run: () => require('../feed/notify').refreshAndNotify(new Date()),
},
{
name: 'feed-sync', label: 'Linked products: fetch events from the products shown here', cron: '*/15 * * * *', env: 'FEED_JOBS_ENABLED',
run: () => require('../feed/sync').syncAll(new Date()),
},
{
name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED',
run: () => require('../utils/retention').runRetention(new Date()),
@@ -147,6 +155,8 @@ function isNoop(value) {
*/
const TASKS = {
'feedback-send': (data) => require('../utils/feedback').runFeedbackTask(data),
// A linked product said its events changed (event.changed): fetch its feed now.
'feed-sync-link': (data) => require('../feed/sync').syncOne(String(data.installId || '')),
};
async function runTask(name, data) {
+186
View File
@@ -0,0 +1,186 @@
/**
* Connect and Disconnect (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2).
*
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in
* this site's own cached `linkedProducts` (same church), signed with the key the Hub listed for
* it. The Hub isn't called while connecting. Both sides then hold the same secret, which signs the
* calls between them (the `event.changed` webhook).
*/
import {
LINK_PATHS,
LINK_SCHEMA,
linkConnectedSchema,
linkConnectSchema,
linkDisconnectSchema,
type LinkConnect,
type LinkConnected,
type LinkDisconnect,
type hub,
} from '@crosscode/contracts';
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import { hubInstallId, siteUrl } from '../feed/context';
import { callSibling, LinkCallError, siblingUrl } from './http';
import { keyPair, listedProduct } from './store';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { encrypt } = require('../utils/encryption') as { encrypt(v: string): string };
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
/* eslint-enable @typescript-eslint/no-require-imports */
export class LinkError extends Error {
constructor(message: string, public code: string, public status = 400) {
super(message);
}
}
const NONCE_KEEP_MS = 60 * 60 * 1000;
type Self = { installId: string; url: string; privateKeyPem: string };
async function self(): Promise<Self> {
const installId = await hubInstallId();
if (!installId) throw new LinkError('This site isn\'t connected to the Hub, so it can\'t link to other products yet.', 'LINKS_UNAVAILABLE', 503);
const url = await siteUrl();
if (!/^https?:\/\//.test(url)) throw new LinkError('Set the site\'s web address first (Site settings → Organisation).', 'LINKS_UNAVAILABLE', 503);
const { privateKeyPem } = await keyPair();
return { installId, url, privateKeyPem };
}
const party = (s: Self) => ({ product: 'events' as const, installId: s.installId, url: s.url });
/** Records a nonce; false when it was seen before (a replay). Old nonces are cleaned up. */
async function firstUse(nonce: string, now: Date): Promise<boolean> {
await prisma.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
try {
await prisma.linkNonce.create({ data: { nonce, seenAt: now } });
return true;
} catch (e) {
if ((e as { code?: string })?.code === 'P2002') return false;
throw e;
}
}
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) {
await logAdminAction({
actorId: actor?.id ?? null,
actorRole: actor?.role ?? 'linked_product',
action,
targetType: 'product_link',
targetId: link.installId,
metadata: { product: link.product, ...metadata },
ip,
});
}
async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedById: string | null, now: Date) {
const data = { product: sibling.product, url: sibling.url, publicKey: sibling.publicKey, secret: encrypt(secret), connectedAt: now, connectedById, lastSyncError: null };
return prisma.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
}
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
schema: LINK_SCHEMA,
type: 'link.connect',
from: party(me),
to: { installId: sibling.installId },
secret,
issuedAt: now.toISOString(),
nonce: newLinkNonce(),
}, me.privateKeyPem);
let reply: unknown;
try {
reply = await callSibling(await siblingUrl(sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
} catch (e) {
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
throw e;
}
const parsed = linkConnectedSchema.safeParse(reply);
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
const r: LinkConnected = parsed.data;
const check = verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: new Date() });
if (!check.ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
}
const link = await saveLink(sibling, secret, actor.id, now);
await audit('product_link_connected', link, actor, ip, { by: 'this_site' });
return link;
}
// ─── A sibling connects to this site ───────────────────────────────────────────
/** Answers `POST /api/links/v1/connect`. Throws LinkError (with the code the sibling is told). */
export async function acceptConnect(body: unknown, ip: string | null, now = new Date()): Promise<LinkConnected> {
const parsed = linkConnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(m.from.installId);
if (!sibling || sibling.product !== m.from.product) {
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
const link = await saveLink(sibling, m.secret, null, now);
await audit('product_link_connected', link, null, ip, { by: 'sibling' });
return signLink<Omit<LinkConnected, 'signature'>>({
schema: LINK_SCHEMA,
type: 'link.connected',
from: party(me),
to: { installId: sibling.installId },
inReplyTo: m.nonce,
issuedAt: new Date().toISOString(),
nonce: newLinkNonce(),
}, me.privateKeyPem);
}
// ─── Disconnect ───────────────────────────────────────────────────────────────
/** This site ends a link. The local link goes even if the sibling can't be reached. */
export async function disconnectFrom(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()): Promise<{ siblingTold: boolean; message: string | null }> {
const link = await prisma.productLink.findUnique({ where: { installId } });
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
let siblingTold = false;
let problem: string | null = null;
try {
const me = await self();
const message = signLink<Omit<LinkDisconnect, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: now.toISOString(), nonce: newLinkNonce(),
}, me.privateKeyPem);
await callSibling(await siblingUrl(link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
siblingTold = true;
} catch (e) {
problem = (e as Error).message;
}
// Its imported events go with it (ImportedEvent cascades).
await prisma.productLink.delete({ where: { installId } });
await audit('product_link_disconnected', link, actor, ip, { by: 'this_site', siblingTold });
return { siblingTold, message: problem };
}
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
export async function acceptDisconnect(body: unknown, ip: string | null, now = new Date()): Promise<void> {
const parsed = linkDisconnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const link = await prisma.productLink.findUnique({ where: { installId: m.from.installId } });
// Already gone: nothing to do, and nothing to tell (the sibling just wants it ended).
if (!link) return;
const check = verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now });
if (!check.ok) throw new LinkError('The signature doesn\'t match this link.', check.code, 401);
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
await prisma.productLink.delete({ where: { installId: link.installId } });
await audit('product_link_disconnected', link, null, ip, { by: 'sibling' });
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Calls to a linked product: only to a public https address the Hub listed (the same rule as
* outbound webhooks, utils/webhooks.js: private addresses refused unless WEBHOOKS_ALLOW_PRIVATE
* is set for local testing), redirects not followed, a timeout, and a size limit on the answer.
*/
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { assertPublicHost } = require('../utils/webhooks') as { assertPublicHost(hostname: string): Promise<void> };
/* eslint-enable @typescript-eslint/no-require-imports */
export const TIMEOUT_MS = 15000;
const MAX_BYTES = 5 * 1024 * 1024;
export class LinkCallError extends Error {
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
super(message);
}
}
const allowHttp = () => String(process.env.WEBHOOKS_ALLOW_PRIVATE || '').toLowerCase() === 'true';
/** The address of `path` on a sibling, after checking where it points. */
export async function siblingUrl(base: string, path: string, query: Record<string, string> = {}): Promise<URL> {
let url: URL;
try {
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
} catch {
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
}
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allowHttp())) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
try {
await assertPublicHost(url.hostname);
} catch (e) {
throw new LinkCallError((e as Error).message, 'PRIVATE_ADDRESS', 400);
}
return url;
}
async function readLimited(res: Response): Promise<string> {
const length = Number(res.headers.get('content-length') || 0);
if (length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
const text = await res.text();
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
return text;
}
/** A JSON request to a sibling. Throws LinkCallError with the sibling's own message and code on a 4xx/5xx. */
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
let res: Response;
try {
res = await fetch(url, {
method: init.method,
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
body: init.body,
redirect: 'manual',
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (e) {
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error)?.message || e}`, 'UNREACHABLE');
}
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
const text = await readLimited(res);
let data: unknown = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
}
if (!res.ok) {
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
}
return data;
}
+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;
}
+89
View File
@@ -0,0 +1,89 @@
/**
* This site's Ed25519 key pair and the church's other products as the Hub last listed them
* (docs/EVENTS-2.4-PLAN.md §1–2). Kept in AppSetting, out of the generic settings endpoints
* (hub/client.js HUB_KEYS):
* hub_private_key (encrypted PKCS#8 PEM), hub_public_key (SPKI PEM), hub_public_key_status
* (the Hub's last publicKeyStatus), hub_linked_products (JSON, from the last heartbeat).
* The key pair is made once and never changed: the Hub keeps the first key it saw, and every
* linked product checks this site's messages against it.
*/
import { hub } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
type LinkedProduct = hub.LinkedProduct;
export const KEY_SETTINGS = ['hub_private_key', 'hub_public_key', 'hub_public_key_status', 'hub_linked_products'] as const;
async function read(key: string): Promise<string | null> {
const row = await prisma.appSetting.findUnique({ where: { key } });
return row?.value ?? null;
}
async function write(key: string, value: string | null): Promise<void> {
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
}
let made: Promise<{ publicKeyPem: string; privateKeyPem: string }> | null = null;
/** This site's key pair, made the first time it's needed. */
export function keyPair(): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
if (!made) {
made = (async () => {
const [priv, pub] = await Promise.all([read('hub_private_key'), read('hub_public_key')]);
if (priv && pub) return { privateKeyPem: decrypt(priv), publicKeyPem: pub };
const pair = generateEd25519();
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
await write('hub_private_key', encrypt(pair.privateKeyPem));
await write('hub_public_key', publicKeyPem);
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
})().catch((e) => {
made = null;
throw e;
});
}
return made;
}
/** For tests. */
export function forgetKeyPair(): void {
made = null;
}
/** `saved` / `matches` / `mismatch` from the Hub, or null (not sent yet, or a Hub before 2.2.0). */
export async function publicKeyStatus(): Promise<string | null> {
return read('hub_public_key_status');
}
export async function setPublicKeyStatus(status: string | null): Promise<void> {
await write('hub_public_key_status', status);
}
/** The church's other installs as the Hub last listed them (an empty list if it never did). */
export async function linkedProducts(): Promise<LinkedProduct[]> {
const raw = await read('hub_linked_products');
if (!raw) return [];
try {
const list = JSON.parse(raw);
return Array.isArray(list) ? list.filter((l) => hub.linkedProductSchema.safeParse(l).success) : [];
} catch {
return [];
}
}
/** Saves the list from a v2 heartbeat or register reply. Entries that don't fit the contract are left out. */
export async function saveLinkedProducts(list: unknown): Promise<LinkedProduct[]> {
if (!Array.isArray(list)) return linkedProducts();
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data as LinkedProduct).slice(0, 10);
await write('hub_linked_products', JSON.stringify(clean));
return clean;
}
export async function listedProduct(installId: string): Promise<LinkedProduct | null> {
return (await linkedProducts()).find((l) => l.installId === installId) ?? null;
}
+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) } };
},
});
@@ -3,6 +3,7 @@ const mockSettings = new Map();
jest.mock('../src/config/db', () => ({
appSetting: {
findMany: jest.fn(async ({ where }) => [...mockSettings].filter(([key]) => where.key.in.includes(key)).map(([key, value]) => ({ key, value }))),
findUnique: jest.fn(async ({ where }) => (mockSettings.has(where.key) ? { key: where.key, value: mockSettings.get(where.key) } : null)),
upsert: jest.fn(async ({ where, create }) => { mockSettings.set(where.key, create.value); }),
deleteMany: jest.fn(async ({ where }) => { mockSettings.delete(where.key); }),
},
@@ -0,0 +1,486 @@
// 2.4.0 (docs/EVENTS-2.4-PLAN.md §8): the event feed, Linked products / Connect, showing events
// from linked products, and the v2 heartbeat. In-memory database (tests/support/fakeFeedDb.js).
jest.mock('../src/config/db', () => require('./support/fakeFeedDb'));
jest.mock('../src/utils/settingsCache', () => {
const db = require('./support/fakeFeedDb');
return {
getSetting: async (key, fallback = '') => (db.t.appSetting.get(key)?.value ?? fallback),
getSettingSync: () => '',
invalidate: () => {},
warmCache: async () => {},
ENCRYPTED_KEYS: new Set(),
};
});
const mockSold = new Map();
jest.mock('../src/utils/stock', () => ({ takenCount: async ({ eventOptionId, sessionId }) => mockSold.get(sessionId ? `${eventOptionId}:${sessionId}` : eventOptionId) || 0 }));
const mockTasks = [];
jest.mock('../src/jobs', () => ({ enqueueTask: async (name, data) => { mockTasks.push([name, data]); return { queued: true }; } }));
process.env.WEBHOOKS_ALLOW_PRIVATE = 'true';
process.env.FRONTEND_URL = 'https://events.hope.test';
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
const express = require('express');
const request = require('supertest');
const { eventSchema, eventFeedSchema, linkConnectSchema, hub: hubContract } = require('@crosscode/contracts');
const signing = require('@crosscode/contracts/signing');
const db = require('./support/fakeFeedDb');
const path = require('path');
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const contractSample = (name) => JSON.parse(require('fs').readFileSync(path.join(SAMPLES, name), 'utf8'));
const { encrypt } = require('../src/utils/encryption');
const { buildCrosscodeEvent, plainToMarkdown, absolute } = require('../src/feed/build');
const { refreshFeed, feedResponse } = require('../src/feed/entries');
const { syncLink } = require('../src/feed/sync');
const connect = require('../src/links/connect');
const store = require('../src/links/store');
const { crossProductRouter } = require('../src/links/routes');
const EVENTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
const WEBSITE_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
const WEBSITE_URL = 'https://www.hope.test';
const NOW = new Date('2026-11-20T10:00:00.000Z');
const DAY = 24 * 3600e3;
const ctx = (over = {}) => ({ installId: EVENTS_ID, baseUrl: 'https://events.hope.test', timezone: 'Africa/Johannesburg', campusesOn: false, now: NOW, ...over });
let n = 0;
const uuid = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`;
function eventRow(over = {}) {
const id = over.id || uuid();
return {
id,
title: 'Youth Camp',
description: 'Three days away.\nBring a *sleeping bag*.',
startDate: new Date(NOW.getTime() + 30 * DAY),
endDate: new Date(NOW.getTime() + 32 * DAY),
goLiveAt: new Date(NOW.getTime() - DAY),
registrationDeadline: null,
picture: '/uploads/camp.jpg',
location: 'Camp Wartburg',
requiresRegistration: true,
waitlistEnabled: false,
scheduleType: 'single',
attendanceMode: 'whole',
lateJoinEnabled: false,
lateJoinUntilSessionId: null,
kidsOptionId: null,
volunteerOptionId: null,
isActive: true,
isHidden: false,
campus: null,
series: null,
sessions: [],
eventOptions: [
{ id: `${id}-adult`, price: 450, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
{ id: `${id}-child`, price: 300, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
{ id: `${id}-tshirt`, price: 120, isMainTicket: false, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
],
...over,
};
}
const keys = { events: signing.generateEd25519(), website: signing.generateEd25519() };
const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
async function setUpSite({ linked = true } = {}) {
db.reset();
store.forgetKeyPair();
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
if (linked) await store.saveLinkedProducts([{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }]);
}
beforeEach(async () => {
mockSold.clear();
mockTasks.length = 0;
await setUpSite();
delete global.fetch;
});
// ─── Building crosscode.event/1 ───────────────────────────────────────────────
describe('crosscode.event/1 from an event', () => {
test('a ticketed event passes the contract, with the lowest main ticket as the price', () => {
const { event, priceRangeCents } = buildCrosscodeEvent(eventRow(), new Map(), ctx());
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
expect(event.origin).toEqual({ product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${event.id}` });
expect(event.registration).toMatchObject({ mode: 'origin', status: 'open', priceFrom: { amountCents: 30000, currency: 'ZAR' } });
expect(priceRangeCents).toEqual({ lowCents: 30000, highCents: 45000 });
expect(event.imageUrl).toBe('https://events.hope.test/api/uploads/camp.jpg');
expect(event.location).toEqual({ name: 'Camp Wartburg', address: null, onlineUrl: null });
});
test('never carries the contact person, kids or volunteer tickets', () => {
const row = eventRow({ contactName: 'Jane', contactPhone: '082', contactEmail: 'jane@x.co.za' });
row.kidsOptionId = row.eventOptions[1].id;
row.eventOptions[1].price = 0;
const json = JSON.stringify(buildCrosscodeEvent(row, new Map(), ctx()).event);
expect(json).not.toMatch(/Jane|082|jane@/);
expect(buildCrosscodeEvent(row, new Map(), ctx()).event.registration.priceFrom).toEqual({ amountCents: 45000, currency: 'ZAR' });
});
test.each([
['not_open', { goLiveAt: new Date(NOW.getTime() + DAY) }, new Map()],
['closed', { registrationDeadline: new Date(NOW.getTime() - 3600e3) }, new Map()],
])('registration %s', (status, over, avail) => {
expect(buildCrosscodeEvent(eventRow(over), avail, ctx()).event.registration.status).toBe(status);
});
test('full when every main ticket is limited and sold out; waitlist when it has one', () => {
const row = eventRow();
row.eventOptions[0].stockLimit = 10;
row.eventOptions[1].stockLimit = 5;
const soldOut = new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 0]]);
expect(buildCrosscodeEvent(row, soldOut, ctx()).event.registration.status).toBe('full');
expect(buildCrosscodeEvent({ ...row, waitlistEnabled: true }, soldOut, ctx()).event.registration.status).toBe('waitlist');
// One main ticket still has places: open.
expect(buildCrosscodeEvent(row, new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 2]]), ctx()).event.registration.status).toBe('open');
});
test('contact-only and free events', () => {
expect(buildCrosscodeEvent(eventRow({ requiresRegistration: false }), new Map(), ctx()).event.registration).toEqual({ mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null });
const free = eventRow();
for (const o of free.eventOptions) o.price = 0;
const built = buildCrosscodeEvent(free, new Map(), ctx());
expect(built.event.registration.priceFrom).toBeNull();
expect(built.priceRangeCents).toBeNull();
});
test('a multi-day event: sessions, and start/end from the sessions that still run', () => {
const s = (d, cancelled = false) => ({ id: uuid(), label: `Week ${d}`, startsAt: new Date(NOW.getTime() + d * 7 * DAY), endsAt: new Date(NOW.getTime() + d * 7 * DAY + 2 * 3600e3), location: null, cancelledAt: cancelled ? NOW : null });
const sessions = [s(1), s(2), s(3, true)];
const { event } = buildCrosscodeEvent(eventRow({ scheduleType: 'sessions', sessions }), new Map(), ctx());
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
expect(event.sessions).toHaveLength(3);
expect(event.endsAt).toBe(sessions[1].endsAt.toISOString());
});
test('an online event, and the campus only while campuses are on', () => {
const row = eventRow({ location: 'https://youtube.com/live/abc', campus: { slug: 'meyerton', name: 'Meyerton' } });
expect(buildCrosscodeEvent(row, new Map(), ctx()).event).toMatchObject({ location: { onlineUrl: 'https://youtube.com/live/abc' }, campus: null });
expect(buildCrosscodeEvent(row, new Map(), ctx({ campusesOn: true })).event.campus).toEqual({ slug: 'meyerton', name: 'Meyerton' });
});
test('plain text descriptions read the same as markdown', () => {
expect(plainToMarkdown('Bring a *sleeping bag*\n- not a list\n1. not numbered\n\n# not a heading')).toBe('Bring a \\*sleeping bag\\* \n\\- not a list \n1\\. not numbered\n\n\\# not a heading');
expect(plainToMarkdown(' ')).toBeNull();
expect(absolute('https://e.test', 'https://cdn.test/x.jpg')).toBe('https://cdn.test/x.jpg');
});
});
// ─── The published feed ───────────────────────────────────────────────────────
describe('the feed', () => {
const put = (row) => db.t.event.set(row.id, row);
test('publishes public events, and updatedSince returns exactly what changed', async () => {
const a = eventRow();
const hidden = eventRow({ isHidden: true });
const later = eventRow({ goLiveAt: new Date(NOW.getTime() + 2 * 3600e3) });
[a, hidden, later].forEach(put);
const first = await refreshFeed(NOW);
expect(first.changed).toEqual([a.id]);
const full = await feedResponse(null, NOW);
expect(eventFeedSchema.safeParse(full).success).toBe(true);
expect(full.events.map((e) => e.id)).toEqual([a.id]);
// Nothing changed: nothing new since.
const t1 = new Date(NOW.getTime() + 60e3);
expect((await refreshFeed(t1)).changed).toEqual([]);
expect((await feedResponse(NOW, t1)).events).toEqual([]);
// Going live changes no Event row, but shows up.
const t2 = new Date(NOW.getTime() + 3 * 3600e3);
expect((await refreshFeed(t2)).changed).toEqual([later.id]);
expect((await feedResponse(t1, t2)).events.map((e) => e.id)).toEqual([later.id]);
});
test('selling out is a change; deactivating puts the event in deleted', async () => {
const a = eventRow();
a.eventOptions[0].stockLimit = 2;
a.eventOptions[1].stockLimit = 2;
put(a);
await refreshFeed(NOW);
mockSold.set(a.eventOptions[0].id, 2);
mockSold.set(a.eventOptions[1].id, 2);
const t1 = new Date(NOW.getTime() + 60e3);
expect((await refreshFeed(t1)).changed).toEqual([a.id]);
const after = await feedResponse(NOW, t1);
expect(after.events[0].registration.status).toBe('full');
expect(after.events[0].updatedAt).toBe(t1.toISOString());
put({ ...a, isActive: false });
const t2 = new Date(NOW.getTime() + 120e3);
expect((await refreshFeed(t2)).removed).toEqual([a.id]);
const gone = await feedResponse(t1, t2);
expect(gone.events).toEqual([]);
expect(gone.deleted).toEqual([{ id: a.id, deletedAt: t2.toISOString() }]);
// A full fetch no longer lists it.
expect((await feedResponse(null, t2)).events).toEqual([]);
});
test('an event that ended a month ago drops out quietly (not deleted)', async () => {
const a = eventRow({ startDate: new Date(NOW.getTime() - 2 * DAY), endDate: new Date(NOW.getTime() - DAY) });
put(a);
await refreshFeed(NOW);
const later = new Date(NOW.getTime() + 31 * DAY);
const r = await refreshFeed(later);
expect(r.removed).toEqual([]);
expect((await feedResponse(NOW, later)).deleted).toEqual([]);
expect(db.t.feedEntry.has(a.id)).toBe(false);
});
test('without a Hub install id there is no feed', async () => {
db.t.appSetting.delete('hub_install_id');
put(eventRow());
expect(await refreshFeed(NOW)).toEqual({ changed: [], removed: [], skipped: [] });
});
});
// ─── Connect ──────────────────────────────────────────────────────────────────
function connectMessage(over = {}, key = keys.website) {
return signing.signLink({
schema: 'crosscode.link/1',
type: 'link.connect',
from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL },
to: { installId: EVENTS_ID },
secret: signing.newLinkSecret(),
issuedAt: new Date().toISOString(),
nonce: signing.newLinkNonce(),
...over,
}, key.privateKeyPem);
}
describe('Connect from a linked product', () => {
test('a listed product connects; the reply is signed with this site\'s key and echoes the nonce', async () => {
const m = connectMessage();
const reply = await connect.acceptConnect(m, '1.2.3.4');
expect(signing.verifyLink(reply, pem(keys.events))).toEqual({ ok: true });
expect(reply).toMatchObject({ type: 'link.connected', inReplyTo: m.nonce, to: { installId: WEBSITE_ID }, from: { product: 'events', installId: EVENTS_ID } });
const link = db.t.productLink.get(WEBSITE_ID);
expect(link).toMatchObject({ product: 'website', url: WEBSITE_URL, connectedById: null });
expect(db.t.audit.map((a) => a.action)).toEqual(['product_link_connected']);
});
test.each([
['not listed by the Hub', async () => { await store.saveLinkedProducts([]); return connectMessage(); }, 'NOT_LINKED'],
['signed with another key', async () => connectMessage({}, signing.generateEd25519()), 'BAD_SIGNATURE'],
['too old', async () => connectMessage({ issuedAt: new Date(Date.now() - 10 * 60e3).toISOString() }), 'STALE_REQUEST'],
['for another install', async () => connectMessage({ to: { installId: WEBSITE_ID } }), 'WRONG_INSTALL'],
['claiming another product', async () => connectMessage({ from: { product: 'app', installId: WEBSITE_ID, url: WEBSITE_URL } }), 'NOT_LINKED'],
['not a link message', async () => ({ hello: 'world' }), 'INVALID_REQUEST'],
])('refused when %s', async (_name, make, code) => {
await expect(connect.acceptConnect(await make(), null)).rejects.toMatchObject({ code });
expect(db.t.productLink.size).toBe(0);
});
test('a replayed message is refused', async () => {
const m = connectMessage();
await connect.acceptConnect(m, null);
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
});
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
await connect.acceptConnect(connectMessage(), null);
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
const msg = (key) => signing.signLink({ schema: 'crosscode.link/1', type: 'link.disconnect', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce() }, key.privateKeyPem);
await expect(connect.acceptDisconnect(msg(signing.generateEd25519()), null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
await connect.acceptDisconnect(msg(keys.website), null);
expect(db.t.productLink.size).toBe(0);
expect(db.t.importedEvent.size).toBe(0);
});
});
describe('Connect from this site', () => {
const admin = { id: 'admin-1', role: 'admin' };
function siblingAnswers(make) {
global.fetch = jest.fn(async (url, init) => {
const body = JSON.parse(init.body);
expect(String(url)).toBe(`${WEBSITE_URL}/api/links/v1/connect`);
expect(linkConnectSchema.safeParse(body).success).toBe(true);
expect(signing.verifyLink(body, pem(keys.events))).toEqual({ ok: true });
const reply = make(body);
return new Response(JSON.stringify(reply.body), { status: reply.status || 200, headers: { 'content-type': 'application/json' } });
});
}
const goodReply = (body, key = keys.website, over = {}) => ({
body: signing.signLink({ schema: 'crosscode.link/1', type: 'link.connected', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, inReplyTo: body.nonce, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce(), ...over }, key.privateKeyPem),
});
test('connects when the sibling answers, signed with its listed key', async () => {
let sentSecret;
siblingAnswers((body) => { sentSecret = body.secret; return goodReply(body); });
await connect.connectTo(WEBSITE_ID, admin, null);
const link = db.t.productLink.get(WEBSITE_ID);
expect(link.connectedById).toBe('admin-1');
expect(require('../src/utils/encryption').decrypt(link.secret)).toBe(sentSecret);
});
test.each([
['signed with another key', (body) => goodReply(body, signing.generateEd25519())],
['for another message', (body) => goodReply(body, keys.website, { inReplyTo: signing.newLinkNonce() })],
])('refuses an answer %s', async (_name, make) => {
siblingAnswers(make);
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
expect(db.t.productLink.size).toBe(0);
});
test('passes on the sibling\'s refusal', async () => {
siblingAnswers(() => ({ status: 403, body: { message: 'Not linked yet', code: 'NOT_LINKED' } }));
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
});
test('only to a product the Hub listed', async () => {
await expect(connect.connectTo('3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09', admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
});
});
// ─── Showing events from a linked product ──────────────────────────────────────
describe('events from a linked product', () => {
const sample = () => contractSample('event-simple.json');
const linkRow = () => ({ installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('s'), connectedAt: NOW, connectedById: null, showEvents: true, lastSyncAt: null, lastGoodAt: null, lastSyncError: null });
const feedOf = (events, deleted = []) => ({ schema: 'crosscode.event-feed/1', generatedAt: NOW.toISOString(), events, deleted });
const answer = (body, status = 200) => { global.fetch = jest.fn(async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); };
test('imports its events, skips a bad one and one that claims another origin', async () => {
db.t.productLink.set(WEBSITE_ID, linkRow());
const good = sample();
const bad = { ...sample(), id: 'not-a-uuid' };
const spoofed = { ...sample(), id: uuid(), origin: { ...sample().origin, installId: EVENTS_ID } };
answer(feedOf([good, bad, spoofed]));
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
expect(r).toMatchObject({ ok: true, imported: 1, rejected: 1, skipped: 1 });
expect([...db.t.importedEvent.keys()]).toEqual([`website:${good.id}`]);
expect(String(global.fetch.mock.calls[0][0])).toBe(`${WEBSITE_URL}/api/feed/v1/events`);
expect(db.t.productLink.get(WEBSITE_ID).lastGoodAt.toISOString()).toBe(NOW.toISOString());
});
test('a source that is down keeps its last events and shows the error', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); });
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
expect(r.ok).toBe(false);
expect(db.t.importedEvent.size).toBe(1);
expect(db.t.productLink.get(WEBSITE_ID).lastSyncError).toMatch(/could not be reached/);
// It fetched what changed since a little before the last good fetch.
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
});
test('deleted events go; never re-published in this site\'s own feed', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
const e = sample();
answer(feedOf([e]));
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
answer(feedOf([], [{ id: e.id, deletedAt: NOW.toISOString() }]));
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
expect(db.t.importedEvent.size).toBe(0);
// The feed is built from this site's own events only.
db.t.importedEvent.set('website:y', { key: 'website:y', linkId: WEBSITE_ID, payload: e });
await refreshFeed(NOW);
expect((await feedResponse(null, NOW)).events).toEqual([]);
});
});
// ─── The endpoints other products call ─────────────────────────────────────────
describe('/api/feed/v1 and /api/links/v1', () => {
const app = () => express().use('/api', crossProductRouter());
test('the feed: on by default, 404 when publishing is off, 400 for a bad updatedSince', async () => {
// The route works on the real clock.
const now = Date.now();
db.t.event.set('e', eventRow({ id: uuid(), goLiveAt: new Date(now - DAY), startDate: new Date(now + 10 * DAY), endDate: new Date(now + 11 * DAY) }));
await refreshFeed(new Date());
const res = await request(app()).get('/api/feed/v1/events');
expect(res.status).toBe(200);
expect(eventFeedSchema.safeParse(res.body).success).toBe(true);
expect(res.body.events).toHaveLength(1);
expect((await request(app()).get('/api/feed/v1/events?updatedSince=yesterday')).body.code).toBe('INVALID_REQUEST');
db.t.appSetting.set('feed_publish', { key: 'feed_publish', value: 'false' });
expect((await request(app()).get('/api/feed/v1/events')).status).toBe(404);
});
test('event.changed: checked with the link\'s secret, then a fetch is queued', async () => {
db.t.productLink.set(WEBSITE_ID, { installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('link-secret'), connectedAt: NOW, showEvents: true });
const body = JSON.stringify({ schema: 'crosscode.event-feed/1', type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [uuid()] });
const send = (secret, sender = WEBSITE_ID) => request(app()).post('/api/feed/v1/changed').set('Content-Type', 'application/json')
.set(signing.signedHeaders(signing.LINK_HEADERS, { senderId: sender, secret, rawBody: body })).send(body);
expect((await send('wrong')).status).toBe(401);
expect((await send('link-secret', '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09')).status).toBe(404);
const ok = await send('link-secret');
expect(ok.status).toBe(202);
expect(mockTasks).toEqual([['feed-sync-link', { installId: WEBSITE_ID }]]);
});
test('connect over HTTP, and errors as { message, code }', async () => {
const res = await request(app()).post('/api/links/v1/connect').send(connectMessage());
expect(res.status).toBe(200);
expect(res.body.type).toBe('link.connected');
const bad = await request(app()).post('/api/links/v1/connect').send(connectMessage({}, signing.generateEd25519()));
expect(bad.status).toBe(401);
expect(bad.body).toEqual({ message: expect.any(String), code: 'BAD_SIGNATURE' });
const notJson = await request(app()).post('/api/links/v1/connect').set('Content-Type', 'application/json').send('{oops');
expect(notJson.body.code).toBe('INVALID_REQUEST');
});
});
// ─── The v2 heartbeat ─────────────────────────────────────────────────────────
describe('protocol v2 heartbeat', () => {
const report = require('../src/hub/report');
const sampleHb = contractSample('hub-heartbeat-events.json');
beforeEach(() => {
jest.spyOn(report, 'health').mockResolvedValue({ ...sampleHb.health, jobs: null, pendingMigrations: null });
jest.spyOn(report, 'stats').mockResolvedValue(sampleHb.stats);
});
afterEach(() => jest.restoreAllMocks());
test('fits the contract (gaps in health filled), with the public key until the Hub has it', async () => {
const client = require('../src/hub/client');
const { body, v2 } = await client.heartbeatBody();
expect(v2).toBe(true);
expect(hubContract.heartbeatRequestSchema.safeParse(body).error?.issues ?? []).toEqual([]);
expect(body.publicKey).toBe(pem(keys.events));
await store.setPublicKeyStatus('saved');
expect((await client.heartbeatBody()).body).not.toHaveProperty('publicKey');
await store.setPublicKeyStatus('mismatch');
expect((await client.heartbeatBody()).body.publicKey).toBe(pem(keys.events));
});
test('a Hub that refuses v2 gets the same heartbeat as v1, and v1 for a day', async () => {
const client = require('../src/hub/client');
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
const sent = [];
global.fetch = jest.fn(async (_url, init) => {
const b = JSON.parse(init.body);
sent.push(b.protocolVersion);
if (b.protocolVersion === 2) return new Response(JSON.stringify({ message: 'Protocol 2 is not supported', code: 'UNSUPPORTED_PROTOCOL' }), { status: 400 });
return new Response(JSON.stringify({ licence: 'x', latestVersion: null }), { status: 200 });
});
const r = await client.heartbeat();
expect(r).toMatchObject({ ok: true, protocol: 1 });
expect(sent).toEqual([2, 1]);
await client.heartbeat();
expect(sent).toEqual([2, 1, 1]);
});
test('saves the church\'s other products from the reply', async () => {
const client = require('../src/hub/client');
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
const listed = [{ product: 'app', installId: '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04', url: 'https://app.hope.test', publicKey: pem(keys.website) }, { product: 'bogus' }];
global.fetch = jest.fn(async () => new Response(JSON.stringify({ licence: 'x', latestVersion: null, linkedProducts: listed, publicKeyStatus: 'saved' }), { status: 200 }));
await client.heartbeat();
expect((await store.linkedProducts()).map((l) => l.product)).toEqual(['app']);
expect(await store.publicKeyStatus()).toBe('saved');
});
});
@@ -0,0 +1,115 @@
// An in-memory stand-in for the Prisma client, with just what the feed and Linked products use
// (src/feed, src/links, src/v2/resources/linkedProducts.ts). Where clauses are matched generically
// (AND, equality, in / notIn, gt / gte / lt / lte, not, nested relation filters on `link`).
const t = { appSetting: new Map(), productLink: new Map(), linkNonce: new Map(), importedEvent: new Map(), feedEntry: new Map(), event: new Map(), campus: [], user: [], audit: [] };
// Rows keep their Dates; JSON columns (payload) keep their strings, as Prisma gives them back.
const clone = (v) => (v === undefined ? v : structuredClone(v));
const val = (v) => (v instanceof Date ? v.getTime() : v);
function matchValue(actual, cond) {
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
return Object.entries(cond).every(([op, x]) => {
switch (op) {
case 'in': return x.includes(actual);
case 'notIn': return !x.includes(actual);
case 'gt': return actual != null && val(actual) > val(x);
case 'gte': return actual != null && val(actual) >= val(x);
case 'lt': return actual != null && val(actual) < val(x);
case 'lte': return actual != null && val(actual) <= val(x);
case 'not': return x === null ? actual != null : !matchValue(actual, x);
default: throw new Error(`fakeFeedDb: no operator ${op}`);
}
});
}
return val(actual) === val(cond);
}
function matches(row, where = {}) {
return Object.entries(where || {}).every(([k, cond]) => {
if (k === 'AND') return cond.every((w) => matches(row, w));
if (k === 'link') return matches(t.productLink.get(row.linkId) || {}, cond.is || cond);
return matchValue(row[k], cond);
});
}
const pick = (row, select) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
function sortBy(rows, orderBy) {
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
return [...rows].sort((a, b) => {
for (const o of list) {
const [k, dir] = Object.entries(o)[0];
const d = val(a[k]) < val(b[k]) ? -1 : val(a[k]) > val(b[k]) ? 1 : 0;
if (d) return dir === 'desc' ? -d : d;
}
return 0;
});
}
function table(name, idKey, { include } = {}) {
const m = t[name];
const withIncludes = (row, inc) => {
if (!inc) return row;
const out = { ...row };
if (inc._count) out._count = { importedEvents: [...t.importedEvent.values()].filter((e) => e.linkId === row.installId).length };
if (inc.link) out.link = { ...t.productLink.get(row.linkId) };
return out;
};
return {
findUnique: jest.fn(async ({ where, select }) => { const r = m.get(where[idKey]); return r ? pick(clone(r), select) : null; }),
findFirst: jest.fn(async ({ where, include: inc } = {}) => { const r = [...m.values()].find((x) => matches(x, where)); return r ? withIncludes(clone(r), inc) : null; }),
findMany: jest.fn(async ({ where, select, include: inc, orderBy, take } = {}) => sortBy([...m.values()].filter((x) => matches(x, where)), orderBy).slice(0, take ?? Infinity).map((r) => withIncludes(pick(clone(r), select), inc))),
create: jest.fn(async ({ data }) => {
if (m.has(data[idKey])) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
m.set(data[idKey], clone(data));
return clone(data);
}),
upsert: jest.fn(async ({ where, create, update }) => {
const prev = m.get(where[idKey]);
const row = prev ? { ...prev, ...update } : { ...create };
m.set(where[idKey], clone(row));
return clone(row);
}),
update: jest.fn(async ({ where, data }) => {
const prev = m.get(where[idKey]);
if (!prev) throw Object.assign(new Error('Record to update not found'), { code: 'P2025' });
const row = { ...prev, ...data };
m.set(where[idKey], clone(row));
return clone(row);
}),
delete: jest.fn(async ({ where }) => {
const prev = m.get(where[idKey]);
if (!prev) throw Object.assign(new Error('Record to delete does not exist'), { code: 'P2025' });
m.delete(where[idKey]);
if (name === 'productLink') for (const [k, e] of t.importedEvent) if (e.linkId === where[idKey]) t.importedEvent.delete(k);
return prev;
}),
deleteMany: jest.fn(async ({ where } = {}) => {
let count = 0;
for (const [k, r] of m) if (matches(r, where)) { m.delete(k); count++; }
return { count };
}),
...include,
};
}
const db = {
t,
appSetting: table('appSetting', 'key'),
productLink: table('productLink', 'installId'),
linkNonce: table('linkNonce', 'nonce'),
importedEvent: table('importedEvent', 'key'),
feedEntry: table('feedEntry', 'eventId'),
event: table('event', 'id'),
campus: { findMany: jest.fn(async () => t.campus.map((c) => ({ ...c }))) },
user: { findMany: jest.fn(async ({ where }) => t.user.filter((u) => matches(u, where))) },
adminAuditLog: { create: jest.fn(async ({ data }) => { t.audit.push(data); return data; }) },
reset() {
for (const k of ['appSetting', 'productLink', 'linkNonce', 'importedEvent', 'feedEntry', 'event']) t[k].clear();
t.campus.length = 0; t.user.length = 0; t.audit.length = 0;
},
};
module.exports = db;
+3
View File
@@ -10,6 +10,8 @@
"api:types": "openapi-typescript src/lib/api-v2/openapi.json -o src/lib/api-v2/schema.d.ts"
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@dnd-kit/core": "^6.3.1",
"@hookform/resolvers": "^5.2.1",
"@radix-ui/react-accordion": "^1.2.11",
@@ -42,6 +44,7 @@
"react-day-picker": "^9.8.1",
"react-dom": "^19.3.1",
"react-hook-form": "^7.62.0",
"react-markdown": "^10.1.0",
"react-webcam": "^7.2.0",
"tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7",
File diff suppressed because it is too large Load Diff
+825
View File
@@ -7326,6 +7326,178 @@ export interface paths {
patch?: never;
trace?: never;
};
"/linked-products": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 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.
*
* **Who:** Admins only.
*/
get: operations["getLinked-products"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-products/settings": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* 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).
*
* **Who:** Admins only.
*/
put: operations["putLinked-productsSettings"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-products/{installId}/connect": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postLinked-productsInstallIdConnect"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-products/{installId}/disconnect": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postLinked-productsInstallIdDisconnect"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-products/{installId}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
put: operations["putLinked-productsInstallId"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-products/{installId}/sync": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Fetch a product's events now
* @description **Who:** Admins only.
*/
post: operations["postLinked-productsInstallIdSync"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-events": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 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.
*
* **Who:** Anyone.
*/
get: operations["getLinked-events"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/linked-events/{product}/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* One event from another of the church's products
* @description **Who:** Anyone.
*/
get: operations["getLinked-eventsProductId"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -8217,6 +8389,19 @@ export interface operations {
} & {
[key: string]: unknown;
})[];
/** @description 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. */
crosscodeEvent: ({
/** @constant */
schema: "crosscode.event/1";
id: string;
} & {
[key: string]: unknown;
}) | null;
/** @description The lowest and highest current ticket prices in cents, for the JSON-LD price range (null when free) */
priceRangeCents: {
lowCents: number;
highCents: number;
} | null;
} & {
[key: string]: unknown;
};
@@ -38772,4 +38957,644 @@ export interface operations {
};
};
};
"getLinked-products": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"putLinked-productsSettings": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
publishEvents: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postLinked-productsInstallIdConnect": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The product's Hub install id */
installId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postLinked-productsInstallIdDisconnect": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The product's Hub install id */
installId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
otherSideTold: boolean;
problem: string | null;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"putLinked-productsInstallId": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The product's Hub install id */
installId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
showEvents: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postLinked-productsInstallIdSync": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The product's Hub install id */
installId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
hubConnected: boolean;
/** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */
keyKnownToHub: boolean;
/** @description The Hub has a different key for this site (ask the provider to clear it) */
keyMismatch: boolean;
publishEvents: boolean;
products: {
installId: string;
product: string;
name: string;
url: string;
/** @description In the list the Hub last gave (false: connected before, no longer listed) */
listed: boolean;
publishesEvents: boolean;
/** @description null = not connected */
link: {
/** Format: date-time */
connectedAt: string;
/** @description Who pressed Connect here; null when the other product connected */
connectedBy: string | null;
showEvents: boolean;
lastSyncAt: string | null;
/** @description When its events were last fetched successfully */
lastGoodAt: string | null;
lastSyncError: string | null;
importedEvents: number;
} | null;
}[];
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"getLinked-events": {
parameters: {
query?: {
/** @description A campus slug (its events, church-wide ones and ones for a campus this site doesn't have), or 'all' for church-wide only */
campus?: string;
/** @description How many per page */
limit?: number;
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @description "<product>:<id>", unique across products */
key: string;
product: string;
productName: string;
/** @description The event as crosscode.event/1, as the other product published it */
event: {
/** @constant */
schema: "crosscode.event/1";
id: string;
title: string;
/** Format: date-time */
startsAt: string;
/** Format: date-time */
endsAt: string;
} & {
[key: string]: unknown;
};
}[];
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"getLinked-eventsProductId": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The product the event comes from */
product: "website" | "app";
/** @description The event's id in that product */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @description "<product>:<id>", unique across products */
key: string;
product: string;
productName: string;
/** @description The event as crosscode.event/1, as the other product published it */
event: {
/** @constant */
schema: "crosscode.event/1";
id: string;
title: string;
/** Format: date-time */
startsAt: string;
/** Format: date-time */
endsAt: string;
} & {
[key: string]: unknown;
};
/** @description When the copy was last refreshed from its product */
lastSyncedAt: string | null;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}
+1180 -4
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -7,6 +7,13 @@
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"signing": [
"./dist/signing.d.ts"
]
}
},
"exports": {
".": {
"import": {
+7
View File
@@ -16,6 +16,13 @@ import { schemaName } from "./schema-name";
export const EVENT_SCHEMA = schemaName("event", 1);
export const EVENT_FEED_SCHEMA = schemaName("event-feed", 1);
/**
* Where every product serves its feed and takes the `event.changed` webhook, relative to its
* address (contracts 1.4.0). The feed is public; the webhook is signed with the link's secret
* (`LINK_HEADERS`).
*/
export const FEED_PATHS = { events: "/api/feed/v1/events", changed: "/api/feed/v1/changed" } as const;
export const REGISTRATION_MODES = ["origin", "external", "contact", "none"] as const;
export const REGISTRATION_STATUSES = ["open", "not_open", "closed", "full", "waitlist"] as const;
export const EVENT_STATUSES = ["published", "cancelled"] as const;