Compare commits

..
Author SHA1 Message Date
joshua 78dd903b2d Merge branch 'feat/events-2.4' 2026-11-18 13:02:21 +02:00
joshuaandClaude Opus 5.5 716d47242a Events 2.4.0 frontend, deploy and docs: Linked products, linked events, seo
- Site settings → Linked products (Connect, Show events from, Publish my
  events), help, command palette.
- Events from linked products on /events, the home and campus pages, and
  /events/linked/<product>/<id> (markdown with HTML off, canonical to the
  origin, no JSON-LD, not in the sitemap).
- Event page JSON-LD from @crosscode/seo; lib/eventSchema.ts removed.
- Readiness check for linked products' sync; e2e spec with a fake
  Church Website (not run yet: needs the e2e Postgres).
- crosscode: install and build the shared packages Events uses first
  (an older tag still builds as before); scripts/tests/events.bats.
- Release notes, changelogs, handovers, hub-protocol.md, and the plan's
  "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:58:50 +02:00
joshuaandClaude Opus 5.5 8a930d07c6 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>
2026-11-18 12:24:29 +02:00
joshuaandClaude Opus 5.5 390b80e56e packages/seo: schema.org JSON-LD and meta helpers on @crosscode/contracts
eventJsonLd (crosscode.event/1), churchJsonLd (crosscode.church/1),
canonicalUrl, pageMeta and jsonLdString (ROADMAP-v3 §11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:01:20 +02:00
joshuaandClaude Opus 5.5 4952e2cb0f Contracts 1.4.0: crosscode.link/1 and a public key in the v2 heartbeat
- crosscode.link/1 (link.connect / link.connected / link.disconnect), with
  signLink / verifyLink, PEM conversion, link secrets and nonces.
- The v2 heartbeat can carry the install's publicKey; the reply says
  saved / matches / mismatch (Hub 2.2.0). Never a failed heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:58:26 +02:00
joshua 9d585c94aa Merge branch 'docs/events-2.4-plan' 2026-11-18 11:54:36 +02:00
joshuaandClaude Opus 5.5 0cc72aaaad docs: plan for Events 2.4.0, handovers after 2.3.1 / agent 1.0.1 / Hub 2.1.1
EVENTS-2.4-PLAN.md: protocol v2 (public key in the v2 heartbeat, Hub 2.2.0),
Linked products and Connect (crosscode.link/1, contracts 1.4.0), the event
feed, showing sibling events, and packages/seo. Six decisions to confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:54:36 +02:00
joshuaandClaude Opus 5.5 6db2f439b4 Release events@2.3.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:20:01 +02:00
joshua 28603f2301 Merge branch 'fix/next-16.4.6' 2026-11-18 10:20:00 +02:00
joshuaandClaude Opus 5.5 ee799dec98 Events: Next.js 16.4.6 (security advisories for 16.2.0-16.4.4)
Two advisories about cached data leaking across root params in `use cache` /
`unstable_cache`. Events uses neither, so it wasn't exposed, but `next build` refuses the
affected versions. The root overrides pinned next and eslint-config-next to 16.4.3; both now
16.4.6. Also brings apps/events/package.json up to the release (left at 2.2.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:20:00 +02:00
87 changed files with 8375 additions and 216 deletions
+33
View File
@@ -2,6 +2,39 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@2.4.0, contracts@1.4.0 - unreleased
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first.
### Events (2.4.0)
- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public
event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the
public pages. Details in `apps/events/CHANGELOG.md`.
### Contracts (1.4.0)
- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` /
`verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`.
- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` /
`mismatch`).
- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`).
### packages/seo (new)
- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11).
### Scripts
- `crosscode` (Events): installs and builds the shared packages Events uses before it.
## events@2.3.1 - 2026-11-18
- Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings
`apps/events/package.json` up to the release (it was left at 2.2.0). Details in
`apps/events/CHANGELOG.md`.
## agent@1.0.1 - 2026-11-18
- A `status` job on the central server is answered by the agent itself (its stats, frps and
+49
View File
@@ -5,6 +5,55 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/).
## [2.4.0] - unreleased
Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2,
docs/EVENTS-2.4-PLAN.md). Needs Hub 2.2.0 for the move to protocol v2 (against an older Hub it keeps
working on v1 and Linked products stays empty). contracts 1.4.0.
### Added
- **Protocol v2** (`src/hub/client.js`): register and heartbeat send `product: "events"`; the site
makes an Ed25519 key pair once (`src/links/store.ts`, `hub_private_key` encrypted) and sends its
public key on the heartbeat until the Hub answers `publicKeyStatus: saved | matches`. Installs
registered with v1 move over without their licence key. The reply's `linkedProducts` is cached
(`hub_linked_products`). A Hub that refuses a v2 body gets the same heartbeat as v1, and v1 is
used for a day (`hub_v1_until`), so the licence always refreshes. Update requests and AI calls
stay v1.
- **Linked products** (Site settings → Linked products; `/api/v2/linked-products`): the church's
other products from the Hub, **Connect** / **Disconnect** (`crosscode.link/1` over
`POST /api/links/v1/connect` and `/disconnect`, both directions, Ed25519-signed and checked
against the Hub-listed key, replays refused via `LinkNonce`), per-link **Show events from** and
the site's **Publish my events** (`feed_publish`). Audit log: `product_link_connected`,
`product_link_disconnected`, `feed_publish_toggled`, `feed_show_toggled`.
- **The event feed** `GET /api/feed/v1/events?updatedSince=` (`crosscode.event-feed/1`, public, no
personal information) built from `FeedEntry` (`src/feed/entries.ts`): going live, closing and
selling out are changes even though no `Event` row changes; deactivated events go in `deleted`;
ended events drop out after 30 days without a tombstone. Refreshed by the `feed` job (every 5
minutes), a few seconds after writes to events, tickets and registrations (`config/db.js`), and
before answering when older than a minute. Changes are announced with `event.changed`
(`LINK_HEADERS`, one retry after a minute; the 15-minute poll catches the rest).
- **Showing linked products' events** (`src/feed/sync.ts`, `ImportedEvent`): fetched every 15
minutes (`feed-sync`) and on a valid `POST /api/feed/v1/changed` (`feed-sync-link` task); only
events whose origin matches the link; the last good copy stays when a source is down. Shown on
/events, the home page and campus pages, each with its page `/events/linked/<product>/<id>`
(markdown with HTML off, canonical link to the origin, no JSON-LD, not in the sitemap).
`/api/v2/linked-events`.
- **`@crosscode/seo`** (`packages/seo`): the event page's JSON-LD now comes from
`crosscode.event/1` (`crosscodeEvent` and `priceRangeCents` on `/events/:id/full`);
`frontend/src/lib/eventSchema.ts` is gone. The price range now covers main tickets only (an add-on
used to set the lowest price).
- Readiness: "Events from linked products are up to date".
- `FEED_JOBS_ENABLED` (default `true`). Migration `20261120120000_linked_products`.
## [2.3.1] - 2026-11-18
### Security
- **Next.js 16.4.3 → 16.4.6** (and eslint-config-next), for two advisories about cached data leaking
across root params in `use cache` / `unstable_cache` (affects 16.2.0–16.4.4). Events uses neither,
so it wasn't exposed; `next build` now refuses affected versions, which stopped the 2.3.0 build.
## [2.3.0] - 2026-11-17
Authenticator-app sign-in and recovery codes (ROADMAP-v3 phase 1c), and what installs and
+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. |
+15
View File
@@ -12,6 +12,21 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 2.4.0
- **Ready for the Church Website and App.** When your church has them, your events can show on
them and theirs here, with registration and payments still in Cross Events. Nothing changes until
you have them: Site settings → Linked products then lists them, with a Connect button.
- **Publish my events** (on by default) shares your public events with your connected products,
exactly as they appear on your events page. Hidden events and anyone's details are never shared.
- **Better search results for your events**: Google gets each event's real dates, place and the
price range of its main tickets, from the same data every Cross Code product uses.
## 2.3.1
- **Maintenance update.** An update to the framework the site is built on, with its latest security
fixes. Nothing changes in how you use Cross Events.
## 2.3.0
- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone
+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
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "2.3.0",
"version": "2.3.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -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",
@@ -48,6 +49,7 @@
"zod": "^4.6.7"
},
"devDependencies": {
"@crosscode/seo": "*",
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10",
@@ -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;
}
@@ -91,6 +91,13 @@ async function readiness(now = new Date(), db = prisma) {
lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.',
'/dashboard/admin/settings?tab=backups');
// Linked products (2.4.0): a product whose events are shown here, but that hasn't answered for a day.
const shown = await (db.productLink?.findMany({ where: { showEvents: true }, select: { url: true, lastGoodAt: true, lastSyncError: true, connectedAt: true } }) ?? Promise.resolve([])).catch(() => []);
const stale = shown.filter(l => l.lastSyncError && now - new Date(l.lastGoodAt || l.connectedAt) > DAY);
add('linked_sync', 'Events from linked products are up to date', stale.length === 0,
stale.length ? `Not fetched for over a day: ${stale.map(l => l.url).join(', ')}. Their last events keep showing.` : `${shown.length} product${shown.length === 1 ? '' : 's'} fetched in the last day`,
'/dashboard/admin/settings?tab=linked', shown.length > 0);
const applicable = checks.filter(c => c.applies);
const passed = applicable.filter(c => c.ok).length;
return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks };
+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,520 @@
// 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');
});
});
// ─── The event page's JSON-LD (@crosscode/seo, replacing frontend/src/lib/eventSchema.ts) ──
describe('event JSON-LD from crosscode.event/1', () => {
test('matches what the event page sent before 2.4.0, with the price range from main tickets only', () => {
const { eventJsonLd } = require('@crosscode/seo');
const row = eventRow({ id: '00000000-0000-4000-8000-0000000000aa' });
const built = buildCrosscodeEvent(row, new Map(), ctx());
// As the page calls it (events/[id]/page.tsx).
const ld = eventJsonLd({ ...built.event, description: row.description }, {
pageUrl: `https://events.hope.test/events/${row.id}`,
organizer: { name: 'Hope Family Church', url: 'https://events.hope.test' },
priceRange: built.priceRangeCents,
offerUrl: `https://events.hope.test/register/${row.id}`,
validFrom: row.goLiveAt.toISOString(),
});
expect(ld).toEqual({
'@context': 'https://schema.org',
'@type': 'Event',
name: 'Youth Camp',
description: row.description,
startDate: row.startDate.toISOString(),
endDate: row.endDate.toISOString(),
eventStatus: 'https://schema.org/EventScheduled',
eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode',
location: { '@type': 'Place', name: 'Camp Wartburg', address: 'Camp Wartburg' },
image: ['https://events.hope.test/api/uploads/camp.jpg'],
url: `https://events.hope.test/events/${row.id}`,
organizer: { '@type': 'Organization', name: 'Hope Family Church', url: 'https://events.hope.test' },
// Before 2.4.0 the add-on T-shirt (R120) made this 120.00–450.00.
offers: { '@type': 'AggregateOffer', lowPrice: '300.00', highPrice: '450.00', priceCurrency: 'ZAR', availability: 'https://schema.org/InStock', url: `https://events.hope.test/register/${row.id}`, validFrom: row.goLiveAt.toISOString() },
});
});
});
@@ -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;
+30 -7
View File
@@ -1,14 +1,16 @@
# Handover — where things stand and how to carry on
Last updated: 2026-11-17, after **2.3.0** (released, tested on a VM, not deployed yet; servers
still run 2.1.1 until they're adopted, see the root [ROLLOUT-1.0.md](../../../docs/ROLLOUT-1.0.md)).
Last updated: 2026-11-18, after **2.3.1** (Next.js 16.4.6 for security advisories, on top of 2.3.0;
released, not deployed yet; servers still run 2.1.1 until they're adopted, see the root
[ROLLOUT-1.0.md](../../../docs/ROLLOUT-1.0.md)).
**This file covers Cross Events only**
(what's been done, where the code lives, known gaps). **The plan for every product and where each
phase stands are in the monorepo's root `docs/`** →
[ROADMAP-v3.md](../../../docs/ROADMAP-v3.md),
[HANDOVER.md](../../../docs/HANDOVER.md) (all products) and
[EVENTS-2.2-PLAN.md](../../../docs/EVENTS-2.2-PLAN.md) (the next Events release:
the move into the monorepo). The Hub protocol is there too ([hub-protocol.md](../../../docs/hub-protocol.md)). How Cross
[EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md) (the next Events release: protocol v2,
Linked products, the event feed and `packages/seo`; the move into the monorepo was
[EVENTS-2.2-PLAN.md](../../../docs/EVENTS-2.2-PLAN.md)). The Hub protocol is there too ([hub-protocol.md](../../../docs/hub-protocol.md)). How Cross
Events got to 2.x is in [ROADMAP-v2.md](./ROADMAP-v2.md); the round before that in
[FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md).
@@ -98,9 +100,10 @@ encrypted settings unreadable or break existing installs.
1. **Roadmap v3**, across every product: see `crosscode-platform/docs/HANDOVER.md` ("Where each
phase stands", "Next up"). **2.2.0** (the move into the monorepo) and **2.3.0** (authenticator
app 2FA and recovery codes, plus what installs from the Hub need) are released (2026-11-17).
Next for Cross Events is **rolling them out** (each install adopted from the Hub), then **2.4.0**
(protocol v2, Linked products, the event feed).
app 2FA and recovery codes, plus what installs from the Hub need) are released (2026-11-17;
**2.3.1** with Next.js 16.4.6 on 2026-11-18). Next for Cross Events is **rolling them out**
(each install adopted from the Hub, on 2.3.1), then **2.4.0** (protocol v2, Linked products,
the event feed), planned in [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md).
- **Deploying:** installs still on 2.1.1 move with `adopt` (Hub → Servers → Installs → Link
existing → Move onto the monorepo, or `crosscode adopt` by hand), never `deploy`. After that,
updates are planned on the Hub (Updates), or `crosscode deploy <church> events` by hand.
@@ -142,6 +145,26 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026
- `backend/src/hub/client.js` `connectFromEnv()`: a site the Hub installed registers by itself on
first start from `HUB_LICENCE_KEY`.
## Where Linked products and the feed live (2.4.0)
Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md).
- **Protocol v2**: `backend/src/hub/client.js` (`heartbeatBody`, the v1 fallback `hub_v1_until`).
The key pair and the Hub's list of the church's products: `backend/src/links/store.ts`.
- **Connect** (`crosscode.link/1`): `backend/src/links/connect.ts` (both directions),
`links/http.ts` (calls to siblings: public addresses only, like webhooks), `links/routes.ts`
(`/api/feed/v1/*`, `/api/links/v1/*`, mounted in `app.js` before the JSON parser).
- **The feed**: `backend/src/feed/build.ts` (an Event as `crosscode.event/1`, also for the event
page's JSON-LD), `feed/entries.ts` (`FeedEntry`, refresh, `changedSoon` from `config/db.js`),
`feed/notify.ts` (`event.changed`), `feed/sync.ts` (fetching linked products' events into
`ImportedEvent`). Jobs `feed`, `feed-sync`; task `feed-sync-link`.
- **Screens**: `frontend/src/components/admin/LinkedProductsTab.tsx` (Site settings → Linked
products), `components/events/LinkedEventCard.tsx`, `lib/linkedEvents.ts`,
`app/events/linked/[product]/[id]/page.tsx`. API: `backend/src/v2/resources/linkedProducts.ts`.
- **Tests**: `backend/tests/linkedProducts.test.js` (in-memory database:
`tests/support/fakeFeedDb.js`), `e2e/linked-products.spec.ts` (a fake Church Website on
localhost:5198).
## Working on this repo
- **Release routine:** branch `feat/<name>` → commit → bump with
+163
View File
@@ -0,0 +1,163 @@
import http from "http";
import path from "path";
import crypto from "crypto";
import { test, expect, loginAs, seed, API } from "./fixtures";
// Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md §8). A fake Church Website
// runs on localhost: the test tells the site the Hub listed it (as a heartbeat would), an admin
// connects it and shows its events, and its event appears on /events with its own page whose
// canonical link points back to the website. Also: this site's own feed, and its event JSON-LD.
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
const backend = path.join(__dirname, "..", "backend");
const { Client } = require(require.resolve("pg", { paths: [backend] }));
const { e2eDatabaseUrl } = require("./support/db-url");
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
const { eventFeedSchema } = require(require.resolve("@crosscode/contracts", { paths: [backend] }));
/* eslint-enable @typescript-eslint/no-require-imports */
const WEBSITE_PORT = 5198;
const WEBSITE_URL = `http://localhost:${WEBSITE_PORT}`;
const WEBSITE_ID = "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02";
const EVENTS_ID = "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c";
const EVENT_ID = "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090";
const websiteKey = signing.generateEd25519();
const websitePem = signing.ed25519PublicToPem(websiteKey.publicKey);
async function sql<T = Record<string, unknown>>(text: string, values: unknown[] = []): Promise<T[]> {
const client = new Client({ connectionString: e2eDatabaseUrl() });
await client.connect();
try {
return (await client.query(text, values)).rows as T[];
} finally {
await client.end();
}
}
const setSetting = (key: string, value: string) =>
sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]);
function websiteEvent() {
const starts = new Date(Date.now() + 10 * 24 * 3600e3);
return {
schema: "crosscode.event/1",
id: EVENT_ID,
origin: { product: "website", installId: WEBSITE_ID, url: `${WEBSITE_URL}/events/carols-by-candlelight` },
status: "published",
updatedAt: new Date().toISOString(),
title: "Carols by Candlelight",
summary: null,
description: "Bring a **blanket** and the family.\n\n<script>alert(1)</script>No booking needed.",
imageUrl: null,
timezone: "Africa/Johannesburg",
startsAt: starts.toISOString(),
endsAt: new Date(starts.getTime() + 2 * 3600e3).toISOString(),
allDay: false,
sessions: [],
location: { name: "Church lawn", address: null, onlineUrl: null },
campus: null,
series: null,
tags: ["christmas"],
registration: { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null },
};
}
test.describe.serial("linked products and the event feed", () => {
let server: http.Server;
const connects: Record<string, unknown>[] = [];
test.beforeAll(async () => {
server = http.createServer((req, res) => {
let body = "";
req.on("data", c => { body += c; });
req.on("end", async () => {
const send = (status: number, json: unknown) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json));
if (req.method === "POST" && req.url === "/api/links/v1/connect") {
const m = JSON.parse(body);
connects.push(m);
// The website checks Cross Events' message with the key the Hub listed for it.
const [row] = await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_public_key'`);
if (!row || !signing.verifyLink(m, row.value).ok) return send(401, { message: "Bad signature", code: "BAD_SIGNATURE" });
return send(200, signing.signLink({
schema: "crosscode.link/1", type: "link.connected",
from: { product: "website", installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID },
inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: crypto.randomBytes(18).toString("base64url"),
}, websiteKey.privateKeyPem));
}
if (req.method === "GET" && req.url?.startsWith("/api/feed/v1/events")) {
return send(200, { schema: "crosscode.event-feed/1", generatedAt: new Date().toISOString(), events: [websiteEvent()], deleted: [] });
}
if (req.method === "POST" && req.url === "/api/links/v1/disconnect") return send(200, { schema: "crosscode.link/1", type: "link.disconnected" });
return send(404, { message: "Not here", code: "NOT_FOUND" });
});
});
await new Promise<void>(resolve => server.listen(WEBSITE_PORT, resolve));
// What a v2 heartbeat would have stored: this site's Hub id and the church's other products.
await setSetting("hub_install_id", EVENTS_ID);
await setSetting("hub_linked_products", JSON.stringify([{ product: "website", installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: websitePem }]));
});
test.afterAll(async () => {
await sql(`DELETE FROM "ProductLink"`);
await sql(`DELETE FROM "FeedEntry"`);
await sql(`DELETE FROM "AppSetting" WHERE key IN ('hub_install_id', 'hub_linked_products', 'feed_publish')`);
await new Promise(resolve => server.close(resolve));
});
test("an admin connects the Church Website and shows its events", async ({ page }) => {
await loginAs(page, "admin");
await page.goto("/dashboard/admin/settings?tab=linked");
const row = page.getByTestId("linked-website");
await expect(row).toContainText("Church Website");
await expect(row).toContainText("Not connected");
await row.getByRole("button", { name: "Connect" }).click();
await expect(page.getByRole("status")).toContainText("Connected to Church Website.");
expect(connects).toHaveLength(1);
expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } });
await row.getByLabel(/Show events from Church Website/).check();
await expect(page.getByRole("status")).toContainText("events are fetched");
await expect(row).toContainText("1 event");
});
test("its event is on /events, with its own page pointing back to the website", async ({ page }) => {
await page.goto("/events");
const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" });
await expect(card).toContainText("From the Church Website");
await card.getByRole("link", { name: "View details" }).click();
await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`));
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Carols by Candlelight");
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute("href", `${WEBSITE_URL}/events/carols-by-candlelight`);
await expect(page.locator("strong", { hasText: "blanket" })).toBeVisible();
// HTML in the description is dropped, never run.
expect(await page.locator("main script").count()).toBe(0);
expect(await page.locator('script[type="application/ld+json"]').count()).toBe(0);
const sitemap = await (await page.request.get("/sitemap.xml")).text();
expect(sitemap).not.toContain("/events/linked/");
});
test("this site's own feed and event JSON-LD", async ({ page, request }) => {
const res = await request.get(`${API}/api/feed/v1/events`);
expect(res.status()).toBe(200);
const feed = await res.json();
expect(eventFeedSchema.safeParse(feed).success).toBe(true);
const ids = feed.events.map((e: { id: string }) => e.id);
expect(ids).toContain(seed().events.free);
expect(ids).not.toContain(EVENT_ID);
expect(JSON.stringify(feed)).not.toMatch(/@e2e\.test/);
await page.goto(`/events/${seed().events.free}`);
const ld = JSON.parse(await page.locator('script[type="application/ld+json"]').innerText());
expect(ld).toMatchObject({ "@context": "https://schema.org", "@type": "Event", url: expect.stringContaining(`/events/${seed().events.free}`) });
});
test("disconnecting removes its events", async ({ page }) => {
await loginAs(page, "admin");
await page.goto("/dashboard/admin/settings?tab=linked");
page.once("dialog", d => d.accept());
await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click();
await expect(page.getByRole("status")).toContainText("Disconnected from Church Website.");
await page.goto("/events");
await expect(page.getByTestId("linked-event-card")).toHaveCount(0);
});
});
+6 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "2.3.0",
"version": "2.3.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -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",
@@ -36,12 +38,13 @@
"date-fns": "^4.1.0",
"idb": "^8.0.4",
"lucide-react": "^0.536.0",
"next": "^16.4.3",
"next": "^16.4.6",
"qrcode": "^1.5.4",
"react": "^19.3.1",
"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",
@@ -55,7 +58,7 @@
"@types/react-dom": "^19.3.0",
"autoprefixer": "^10.4.21",
"eslint": "^10.13.0",
"eslint-config-next": "^16.4.3",
"eslint-config-next": "^16.4.6",
"openapi-typescript": "^7.13.0",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
@@ -4,6 +4,8 @@ import { notFound } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { EventCard } from "@/components/events/EventCard";
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
import { ApiImage } from "@/components/shared/ApiImage";
import { apiFetchListForPrerender, ApiError } from "@/lib/api";
import { mapsSearchUrl } from "@/lib/maps";
@@ -42,13 +44,17 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
const campus = await loadCampus(slug);
if (!campus) notFound();
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } });
const [events, linked] = await Promise.all([
apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }),
fetchLinkedEvents(campus.slug),
]);
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const upcoming = (events || [])
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
.sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
const items = mergeByStart(upcoming, linked, e => e.nextSession?.startsAt || e.startDate);
return (
<div className="min-h-screen flex flex-col">
@@ -79,14 +85,16 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
<h2 className="text-xl font-semibold text-gray-900 mb-1">Upcoming events</h2>
<p className="text-sm text-gray-500 mb-6">Events at {campus.name}, and church-wide events for every campus.</p>
{upcoming.length === 0 ? (
{items.length === 0 ? (
<div className="text-center py-16 border rounded-xl bg-gray-50">
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
<p className="text-gray-500 text-sm">No upcoming events at {campus.name} right now — check back soon.</p>
</div>
) : (
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
{upcoming.map(event => <EventCard key={event.id} event={event} />)}
{items.map(item => item.kind === "own"
? <EventCard key={item.event.id} event={item.event} />
: <LinkedEventCard key={item.event.key} item={item.event} />)}
</div>
)}
</main>
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react";
import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
@@ -17,6 +17,7 @@ import { PaymentsTab } from "@/components/admin/PaymentsTab";
import { LicenceTab } from "@/components/admin/LicenceTab";
import { WebhooksTab } from "@/components/admin/WebhooksTab";
import { AiTab } from "@/components/admin/AiTab";
import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab";
import { CampusesTab } from "@/components/admin/CampusesTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
@@ -25,7 +26,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -37,6 +38,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
{ id: "payments", label: "Payments", icon: CreditCard },
{ id: "webhooks", label: "Webhooks", icon: Webhook },
{ id: "linked", label: "Linked products", icon: Link2 },
{ id: "backups", label: "Backups", icon: DatabaseBackup },
{ id: "jobs", label: "Background jobs", icon: Timer },
{ id: "licence", label: "Licence", icon: KeyRound },
@@ -718,6 +720,7 @@ function SiteSettingsPageInner() {
{/* ── Backups ───────────────────────────────────────────────────────── */}
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
{activeTab === "linked" && <LinkedProductsTab active={activeTab === "linked"} />}
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
@@ -54,6 +54,9 @@ type Event = {
attendanceMode?: "whole" | "pick";
sessions?: EventSession[];
registrationClosesAt?: string;
// 2.4.0: the event as crosscode.event/1, what its schema.org JSON-LD is built from (@crosscode/seo).
crosscodeEvent?: CrosscodeEvent | null;
priceRangeCents?: { lowCents: number; highCents: number } | null;
lateJoin?: LateJoinInfo | null;
series?: EventSeriesRef | null;
nextInSeries?: NextInSeries | null;
@@ -69,7 +72,8 @@ import { isPickOption, latePrice, registrationClosesAt, scheduleSummary } from "
import { SessionSchedule } from "@/components/events/SessionSchedule";
import { appUrl, appName } from "@/lib/siteConfig";
import { getServerSettings } from "@/lib/serverSettings";
import { eventJsonLd, jsonLdString } from "@/lib/eventSchema";
import { eventJsonLd, jsonLdString } from "@crosscode/seo";
import type { CrosscodeEvent } from "@crosscode/contracts";
// Tiered low-stock threshold: larger events use a smaller percentage.
// Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made
@@ -188,16 +192,21 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id
const settings = await getServerSettings();
const siteUrl = appUrl.replace(/\/$/, "");
const jsonLd = eventJsonLd(event, {
pageUrl: `${siteUrl}/events/${event.id}`,
imageUrl: event.picture ? resolveToApiOrigin(event.picture) : null,
organizerName: settings.org_name || appName,
siteUrl,
});
// schema.org Event (Google's event results), from the same crosscode.event/1 the feed publishes.
// The description goes in as the plain text it is (the feed's copy is escaped for markdown).
const jsonLd = event.crosscodeEvent
? eventJsonLd({ ...event.crosscodeEvent, description: event.description || null }, {
pageUrl: `${siteUrl}/events/${event.id}`,
organizer: { name: settings.org_name || appName, url: siteUrl },
priceRange: event.priceRangeCents ?? undefined,
offerUrl: `${siteUrl}/register/${event.id}`,
validFrom: event.goLiveAt || null,
})
: null;
return (
<div className="min-h-screen flex flex-col">
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />
{jsonLd && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />}
<Navbar />
<main className="flex-1 py-8 px-4 max-w-6xl mx-auto w-full">
<FunnelTracker eventId={event.id} stage="view" />
@@ -0,0 +1,121 @@
import { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import { ArrowLeft, Calendar, ExternalLink, MapPin, Video } from "lucide-react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { ApiImage } from "@/components/shared/ApiImage";
import { ApiError } from "@/lib/api";
import { apiV2Data } from "@/lib/apiV2";
import { formatDateTimeRange } from "@/lib/date";
import { fromLabel, type LinkedEvent } from "@/lib/linkedEvents";
export const revalidate = 60;
type Linked = LinkedEvent & { lastSyncedAt: string | null };
type Params = { params: Promise<{ product: string; id: string }> };
async function load(product: string, id: string): Promise<Linked | null> {
if (product !== "website" && product !== "app") return null;
try {
return (await apiV2Data("get", "/linked-events/{product}/{id}", { params: { product, id }, nextOptions: { next: { revalidate } } })) as unknown as Linked;
} catch (e) {
if (e instanceof ApiError && (e.status === 404 || e.status === 400)) return null;
throw e;
}
}
/** The description's first paragraph as plain text, for the meta description. */
const plain = (md: string | null) => (md || "").split(/\n\s*\n/)[0]!.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim().slice(0, 200);
export async function generateMetadata({ params }: Params): Promise<Metadata> {
const { product, id } = await params;
const item = await load(product, id);
if (!item) return {};
const e = item.event;
const description = e.summary || plain(e.description) || `${e.title} — ${formatDateTimeRange(e.startsAt, e.endsAt)}`;
return {
title: e.title,
description,
// A copy: search engines are pointed at the event's own page, so they see one event, not two
// (ROADMAP-v3 §11, "Imported events"). It isn't in this site's sitemap either.
alternates: { canonical: e.origin.url },
openGraph: { title: e.title, description, type: "website", url: e.origin.url, ...(e.imageUrl ? { images: [{ url: e.imageUrl }] } : {}) },
twitter: { card: "summary_large_image", title: e.title, description, ...(e.imageUrl ? { images: [e.imageUrl] } : {}) },
};
}
/**
* An event from another of the church's products (2.4.0): shown read-only, with the way to take
* part at the product it comes from. No schema.org JSON-LD here; its own page carries it.
*/
export default async function LinkedEventPage({ params }: Params) {
const { product, id } = await params;
const item = await load(product, id);
if (!item) notFound();
const e = item.event;
const r = e.registration;
const live = e.sessions.filter(s => !s.cancelled);
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-1 py-8 px-4 max-w-4xl mx-auto w-full">
<Link href="/events" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
<ArrowLeft className="w-4 h-4" /> All events
</Link>
{e.imageUrl && <ApiImage src={e.imageUrl} alt={e.title} className="w-full max-h-96 object-cover rounded-2xl mb-6" />}
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
<h1 className="text-3xl font-bold text-gray-900 mt-1">{e.title}</h1>
{e.status === "cancelled" && <p className="mt-2 inline-block rounded-full bg-red-50 px-3 py-1 text-sm font-medium text-red-700">Cancelled</p>}
<div className="mt-4 space-y-2 text-gray-700">
<p className="flex items-center gap-2"><Calendar className="w-4 h-4 shrink-0 text-gray-400" /> {formatDateTimeRange(e.startsAt, e.endsAt)}</p>
{(e.location?.name || e.location?.address) && (
<p className="flex items-center gap-2"><MapPin className="w-4 h-4 shrink-0 text-gray-400" /> {[e.location?.name, e.location?.address].filter(Boolean).join(", ")}</p>
)}
{e.location?.onlineUrl && (
<p className="flex items-center gap-2"><Video className="w-4 h-4 shrink-0 text-gray-400" /> <a href={e.location.onlineUrl} rel="noopener nofollow" className="text-brand-700 underline">Join online</a></p>
)}
{e.campus && <p className="text-sm text-gray-500">{e.campus.name}</p>}
</div>
{live.length > 1 && (
<div className="mt-6">
<h2 className="font-semibold text-gray-900 mb-2">Dates</h2>
<ul className="space-y-1 text-sm text-gray-700">
{live.map(s => <li key={s.id}>{s.label ? `${s.label}: ` : ""}{formatDateTimeRange(s.startsAt, s.endsAt)}{s.location ? ` · ${s.location}` : ""}</li>)}
</ul>
</div>
)}
{e.description && (
<div className="prose prose-sm max-w-none mt-6 text-gray-700">
{/* Markdown with HTML switched off (crosscode.event/1): raw HTML is dropped, links open as plain links. */}
<ReactMarkdown skipHtml components={{ a: ({ href, children }) => <a href={href} rel="noopener nofollow ugc" className="text-brand-700 underline">{children}</a> }}>
{e.description}
</ReactMarkdown>
</div>
)}
<div className="mt-8 rounded-xl border p-4 bg-gray-50">
{(r.mode === "origin" || r.mode === "external") && r.url ? (
<a href={r.url} rel="noopener" className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-white font-medium hover:bg-brand-700">
Register <ExternalLink className="w-4 h-4" aria-hidden />
</a>
) : r.mode === "contact" ? (
<p className="text-sm text-gray-700">No booking here: see the details above for how to take part.</p>
) : (
<p className="text-sm text-gray-700">No booking needed.</p>
)}
<p className="mt-3 text-sm text-gray-600">
This event is run through the {item.productName}.{" "}
<a href={e.origin.url} rel="noopener" className="text-brand-700 underline">See it there</a> for the latest details.
</p>
</div>
</main>
<Footer />
</div>
);
}
+7 -3
View File
@@ -3,6 +3,7 @@ import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { EventsGrid } from "@/components/events/EventsGrid";
import { apiFetchListForPrerender } from "@/lib/api";
import { fetchLinkedEvents } from "@/lib/linkedEvents";
import { Calendar } from "lucide-react";
export const revalidate = 60;
@@ -32,7 +33,10 @@ type Event = {
};
export default async function EventsPage() {
const events = await apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } });
const [events, linked] = await Promise.all([
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
fetchLinkedEvents(),
]);
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
@@ -53,10 +57,10 @@ export default async function EventsPage() {
</div>
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900">All Events</h1>
<p className="text-sm text-gray-500">{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}</p>
<p className="text-sm text-gray-500">{sorted.length + linked.length} upcoming event{sorted.length + linked.length === 1 ? "" : "s"}</p>
</div>
</div>
<EventsGrid events={sorted} />
<EventsGrid events={sorted} linked={linked} />
</main>
<Footer />
</div>
+12 -7
View File
@@ -1,5 +1,7 @@
import Link from "next/link";
import { EventCard } from "@/components/events/EventCard";
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { JoinUsButton } from "@/components/home/JoinUsButton";
@@ -48,9 +50,10 @@ async function getOrgName(): Promise<string> {
}
export default async function HomePage() {
const [events, displayName] = await Promise.all([
const [events, displayName, linked] = await Promise.all([
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
getOrgName(),
fetchLinkedEvents(),
]);
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
@@ -60,6 +63,8 @@ export default async function HomePage() {
return !isNaN(t) && t > now;
});
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
// With events from the church's other products (Linked products), by date.
const items = mergeByStart(sorted, linked, e => e.nextSession?.startsAt || e.startDate);
return (
<div className="min-h-screen flex flex-col">
@@ -72,10 +77,10 @@ export default async function HomePage() {
<div className="absolute -bottom-24 -left-24 w-96 h-96 rounded-full bg-brand-100/40 blur-3xl" />
</div>
<div className="relative max-w-2xl mx-auto px-4">
{sorted.length > 0 && (
{items.length > 0 && (
<div className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full bg-white border border-brand-200 text-brand-700 shadow-sm mb-5">
<CalendarCheck className="w-3.5 h-3.5" />
{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}
{items.length} upcoming event{items.length === 1 ? "" : "s"}
</div>
)}
<h1 className="text-4xl sm:text-5xl font-bold mb-4 text-gray-900">Welcome to {displayName}</h1>
@@ -98,16 +103,16 @@ export default async function HomePage() {
<ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
{sorted.length === 0 ? (
{items.length === 0 ? (
<div className="text-center py-12 border rounded-xl bg-gray-50">
<CalendarCheck className="w-8 h-8 text-gray-300 mx-auto mb-2" />
<p className="text-gray-500 text-sm">No upcoming events right now — check back soon.</p>
</div>
) : (
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
{sorted.slice(0, 3).map(event => (
<EventCard key={event.id} event={event} />
))}
{items.slice(0, 3).map(item => item.kind === "own"
? <EventCard key={item.event.id} event={item.event} />
: <LinkedEventCard key={item.event.key} item={item.event} />)}
</div>
)}
<div className="text-center mt-8 sm:hidden">
@@ -0,0 +1,167 @@
"use client";
import React, { useEffect, useState } from "react";
import { Link2, RefreshCw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
type Overview = V2Result<"/linked-products", "get">["data"];
type Product = Overview["products"][number];
const when = (iso: string | null) =>
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "never";
/** "2 hours ago", for "last synced". */
function ago(iso: string | null): string {
if (!iso) return "never";
const mins = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins} minute${mins === 1 ? "" : "s"} ago`;
const hours = Math.round(mins / 60);
if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
return `${Math.round(hours / 24)} days ago`;
}
/**
* Site settings → Linked products (2.4.0): the church's other Cross Code products (as the Hub
* lists them), Connect / Disconnect, "Show events from" each, and "Publish my events".
*/
export function LinkedProductsTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [data, setData] = useState<Overview | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState<string | null>(null);
useEffect(() => {
if (!active || !token) return;
let alive = true;
apiV2("get", "/linked-products", { authToken: token })
.then(({ data: d }) => { if (alive) setData(d); })
.catch(e => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load linked products." }); });
return () => { alive = false; };
}, [active, token]);
const run = async (key: string, call: () => Promise<{ data: Overview }>, ok: string | ((d: Overview) => string)) => {
setBusy(key);
setMsg(null);
try {
const { data: d } = await call();
setData(d);
setMsg({ ok: true, text: typeof ok === "function" ? ok(d) : ok });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
}
setBusy(null);
};
if (!token) return null;
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
const auth = { authToken: token };
const connect = (p: Product) => run(`c:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/connect", { ...auth, params: { installId: p.installId } }), `Connected to ${p.name}.`);
const disconnect = (p: Product) => {
if (!window.confirm(`Disconnect ${p.name}? Its events stop showing here, and this site's events stop showing there.`)) return;
run(`d:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/disconnect", { ...auth, params: { installId: p.installId } }) as Promise<{ data: Overview & { otherSideTold: boolean; problem: string | null } }>,
(d) => {
const r = d as Overview & { otherSideTold?: boolean; problem?: string | null };
return r.otherSideTold ? `Disconnected from ${p.name}.` : `Disconnected here. ${p.name} couldn't be told (${r.problem || "not reachable"}); disconnect it there too.`;
});
};
const showEvents = (p: Product, on: boolean) => run(`s:${p.installId}`, () => apiV2("put", "/linked-products/{installId}", { ...auth, params: { installId: p.installId }, body: { showEvents: on } }),
on ? `${p.name}'s events are fetched and shown on your events pages.` : `${p.name}'s events are no longer shown here.`);
const syncNow = (p: Product) => run(`y:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/sync", { ...auth, params: { installId: p.installId } }), "Fetched.");
const publish = (on: boolean) => run("publish", () => apiV2("put", "/linked-products/settings", { ...auth, body: { publishEvents: on } }),
on ? "Your events are published for your other products." : "Your events are no longer published.");
return (
<div className="space-y-6">
<div>
<h2 className="flex items-center gap-2 text-lg font-semibold"><Link2 className="h-5 w-5 text-brand-600" aria-hidden /> Linked products</h2>
<p className="mt-1 text-sm text-gray-600">
Your church&apos;s other Cross Code products, such as the Church Website and Church App. Connect them to show your events there, and theirs here.
Registrations and payments always stay in Cross Events.
</p>
</div>
{msg && <p role="status" className={`text-sm ${msg.ok ? "text-green-700" : "text-red-700"}`}>{msg.text}</p>}
{!data.hubConnected && (
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">This site isn&apos;t connected to the Hub yet (Settings → Licence), so it doesn&apos;t know your other products.</div>
)}
{data.hubConnected && data.keyMismatch && (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
The Hub has a different key for this site, so your other products can&apos;t check that messages really come from it. This happens after a server is rebuilt: ask your provider to clear the site&apos;s key on the Hub.
</div>
)}
<div className="rounded-lg border p-4">
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1" checked={data.publishEvents} disabled={busy === "publish"} onChange={e => publish(e.target.checked)} />
<span>
<span className="text-sm font-medium">Publish my events</span>
<span className="block text-sm text-gray-600">Your public events, as they appear on your events page, for your connected products to show. Never anyone&apos;s details.</span>
</span>
</label>
</div>
{data.hubConnected && data.products.length === 0 && (
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">
Your church has no other Cross Code products yet. When it has (for example the{" "}
<a href="https://crosscode.co.za" className="text-brand-700 underline" target="_blank" rel="noopener noreferrer">Church Website</a>), it shows here within 15 minutes.
</div>
)}
{data.products.length > 0 && (
<ul className="space-y-3">
{data.products.map(p => (
<li key={p.installId} className="rounded-lg border p-4" data-testid={`linked-${p.product}`}>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="font-medium">{p.name}</div>
<a href={p.url} target="_blank" rel="noopener noreferrer" className="text-sm text-brand-700 underline">{p.url.replace(/^https?:\/\//, "")}</a>
<div className="mt-1 text-sm text-gray-600">
{p.link
? <>Connected {when(p.link.connectedAt)}{p.link.connectedBy ? ` by ${p.link.connectedBy}` : ` by ${p.name}`}</>
: "Not connected"}
{!p.listed && <span className="ml-1 text-amber-800">· no longer listed by the Hub</span>}
</div>
</div>
<div className="flex gap-2">
{p.link ? (
<button type="button" className="rounded-lg border px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50" disabled={!!busy} onClick={() => disconnect(p)}>Disconnect</button>
) : (
<button type="button" className="rounded-lg bg-brand-600 px-3 py-1.5 text-sm text-white hover:bg-brand-700 disabled:opacity-50" disabled={!!busy || !p.listed} onClick={() => connect(p)}>
{busy === `c:${p.installId}` ? "Connecting…" : "Connect"}
</button>
)}
</div>
</div>
{p.link && p.publishesEvents && (
<div className="mt-3 border-t pt-3">
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1" checked={p.link.showEvents} disabled={!!busy} onChange={e => showEvents(p, e.target.checked)} />
<span>
<span className="text-sm font-medium">Show events from {p.name}</span>
<span className="block text-sm text-gray-600">Its events appear on your events pages, marked as coming from it, with a link to their page there.</span>
</span>
</label>
{p.link.showEvents && (
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-gray-600">
<span>{p.link.importedEvents} event{p.link.importedEvents === 1 ? "" : "s"} · last synced {ago(p.link.lastGoodAt)}</span>
<button type="button" className="inline-flex items-center gap-1 text-brand-700 underline disabled:opacity-50" disabled={!!busy} onClick={() => syncNow(p)}>
<RefreshCw className="h-3.5 w-3.5" aria-hidden /> Fetch now
</button>
{p.link.lastSyncError && <span className="w-full text-amber-800">Last try ({ago(p.link.lastSyncAt)}): {p.link.lastSyncError}. The events from the last good fetch keep showing.</span>}
</div>
)}
</div>
)}
</li>
))}
</ul>
)}
</div>
);
}
@@ -3,12 +3,14 @@
import React, { useState } from "react";
import { CalendarX } from "lucide-react";
import { EventCard } from "@/components/events/EventCard";
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
import { mergeByStart, type LinkedEvent } from "@/lib/linkedEvents";
import { CampusFilter } from "@/components/shared/CampusFilter";
import { useCampuses } from "@/hooks/useCampuses";
import { useAuth } from "@/hooks/useAuth";
import { useExternalEffect } from "@/lib/hooks";
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null };
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null; nextSession?: { startsAt: string } | null };
// The visitor's campus choice, kept in this browser (like the cookie choice).
const STORAGE_KEY = "hope_events_campus";
@@ -23,8 +25,10 @@ function store(value: string) {
/**
* The public events grid with a campus filter (while campuses are on). A campus shows its own
* events plus church-wide ones. Starts on the visitor's last choice, else their home campus.
* Events from linked products (2.4.0) are mixed in by date; a campus also shows linked events for
* no campus or for a campus this site doesn't have.
*/
export function EventsGrid({ events }: { events: GridEvent[] }) {
export function EventsGrid({ events, linked = [] }: { events: GridEvent[]; linked?: LinkedEvent[] }) {
const { enabled, campuses } = useCampuses();
const { user } = useAuth();
const [campus, setCampus] = useState("");
@@ -39,20 +43,28 @@ export function EventsGrid({ events }: { events: GridEvent[] }) {
const choose = (value: string) => { setCampus(value); store(value); };
const shown = enabled && campus ? events.filter(e => !e.campusId || e.campusId === campus) : events;
const chosenSlug = campuses.find(c => c.id === campus)?.slug;
const slugs = new Set(campuses.map(c => c.slug));
const shownLinked = enabled && campus
? linked.filter(l => !l.event.campus || !slugs.has(l.event.campus.slug) || l.event.campus.slug === chosenSlug)
: linked;
const items = mergeByStart(shown, shownLinked, e => e.nextSession?.startsAt || e.startDate);
return (
<>
<div className="mb-6">
<CampusFilter value={campus} onChange={choose} id="events-campus" />
</div>
{shown.length === 0 ? (
{items.length === 0 ? (
<div className="text-center py-16 border rounded-xl bg-gray-50">
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
<p className="text-gray-500 text-sm">{events.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
<p className="text-gray-500 text-sm">{events.length + linked.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
</div>
) : (
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
{shown.map(event => <EventCard key={event.id} event={event} />)}
{items.map(item => item.kind === "own"
? <EventCard key={item.event.id} event={item.event} />
: <LinkedEventCard key={item.event.key} item={item.event} />)}
</div>
)}
</>
@@ -0,0 +1,61 @@
import { Calendar, ExternalLink, MapPin } from "lucide-react";
import { ApiImage } from "@/components/shared/ApiImage";
import { formatDateTimeRange } from "@/lib/date";
import { fromLabel, linkedEventPath, type LinkedEvent } from "@/lib/linkedEvents";
/** The first paragraph of a markdown description as plain text, for a card. */
function teaser(e: LinkedEvent["event"]): string {
const text = e.summary || (e.description || "").split(/\n\s*\n/)[0] || "";
return text.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim();
}
/**
* A card for an event from another of the church's products (Website, App): like EventCard, with
* a "From the Church Website" label. Details open its page here; registering happens where it comes from.
*/
export function LinkedEventCard({ item }: { item: LinkedEvent }) {
const e = item.event;
const r = e.registration;
const place = e.location?.name || e.location?.address || (e.location?.onlineUrl ? "Online" : null);
const action = r.mode === "origin" ? "Register" : r.mode === "external" ? "Register" : null;
return (
<div className="relative border rounded-xl overflow-hidden shadow-sm hover:shadow-md hover:border-brand-200 transition" data-testid="linked-event-card">
<a href={linkedEventPath(item)} className="block">
{e.imageUrl ? (
<ApiImage src={e.imageUrl} alt={e.title} className="h-48 w-full object-cover" />
) : (
<div className="h-48 w-full bg-brand-50 flex items-center justify-center">
<Calendar className="w-10 h-10 text-brand-200" />
</div>
)}
<div className="p-4">
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
<h3 className="text-lg font-semibold hover:underline">{e.title}</h3>
{e.campus && <p className="text-xs text-gray-500 mt-0.5">{e.campus.name}</p>}
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
<Calendar className="w-3.5 h-3.5 shrink-0" />
{formatDateTimeRange(e.startsAt, e.endsAt)}
</p>
{place && (
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
<MapPin className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">{place}</span>
</p>
)}
<p className="text-sm text-gray-600 mt-2 line-clamp-2">{teaser(e)}</p>
</div>
</a>
<div className="px-4 pb-4 flex gap-2">
<a href={linkedEventPath(item)} className="flex-1 text-center text-sm text-gray-700 border rounded-lg py-2 hover:bg-gray-50 transition-colors">
View details
</a>
{action && r.url && (
<a href={r.url} rel="noopener" className="flex-1 inline-flex items-center justify-center gap-1 text-center text-sm text-white bg-brand-600 rounded-lg py-2 hover:bg-brand-700 transition-colors">
{action} <ExternalLink className="w-3.5 h-3.5" aria-hidden />
</a>
)}
</div>
</div>
);
}
@@ -1,5 +1,5 @@
import React from "react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen, Link2 } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
@@ -174,6 +174,27 @@ export const siteSettingsHelpContent: HelpContent = {
</div>
),
},
{
key: "linked",
label: "Linked products",
icon: Link2,
content: (
<div className="space-y-4">
<p>Your church&apos;s other Cross Code products, such as the Church Website and the Church App. The Hub lists them here by itself (within 15 minutes of a new one being set up).</p>
<div className="space-y-4">
<GuideItem icon={Link2} title="Connect" tone="brand">
&quot;Connect&quot; sets up a secure link with that product, so your events can show there and theirs here. Either side can connect or disconnect; the other side shows who did it.
</GuideItem>
<GuideItem icon={Megaphone} title="Publish my events" tone="green">
On by default: your connected products can show your public events, as they appear on your events page, with a link back here to register. Hidden events, people&apos;s details and children&apos;s details are never shared. Registrations and payments always stay in Cross Events.
</GuideItem>
<GuideItem icon={Send} title="Show events from a product" tone="gray">
Tick it to show that product&apos;s events on your events pages, marked as coming from it. They&apos;re fetched every 15 minutes (straight away when they change), and can only be changed where they come from. If that product can&apos;t be reached, its last events keep showing and this tab says when it last synced.
</GuideItem>
</div>
</div>
),
},
{
key: "jobs",
label: "Background jobs",
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"];
};
};
};
};
}
+1 -1
View File
@@ -62,7 +62,7 @@ export const COMMAND_PAGES: CommandPage[] = [
// Settings
...([
["organisation", "Organisation"], ["campuses", "Campuses"], ["branding", "Branding"], ["notifications", "Notifications"],
["email", "Email"], ["legal", "Legal"], ["whatsapp", "WhatsApp"], ["payments", "Payments"], ["webhooks", "Webhooks"],
["email", "Email"], ["legal", "Legal"], ["whatsapp", "WhatsApp"], ["payments", "Payments"], ["webhooks", "Webhooks"], ["linked", "Linked products"],
["backups", "Backups"], ["jobs", "Background jobs"], ["licence", "Licence & updates"], ["ai", "AI helpers"],
] as const).map(([tab, label]): CommandPage => ({ group: "Settings", label: `Settings: ${label}`, href: `/dashboard/admin/settings?tab=${tab}`, roles: ADM, keywords: "site settings" })),
// Reports — every report in the catalogue
@@ -1,85 +0,0 @@
// schema.org Event data for an event page, so Google can show the event with its date,
// venue and ticket link (event rich results / "events near me").
// Checked with https://search.google.com/test/rich-results
type SchemaOption = {
price: number;
stockLimit?: number;
availableCount?: number;
earlyBirdTiers?: { deadline: string; price: number }[];
variants?: { price: number | null; stockLimit?: number; availableCount?: number }[];
};
export type SchemaEvent = {
id: string;
title: string;
description?: string;
startDate: string;
endDate: string;
goLiveAt?: string;
picture?: string;
location?: string | null;
requiresRegistration?: boolean;
eventOptions?: SchemaOption[];
};
/** Today's price of each ticket (early-bird when one is open, else the variant/base price). */
function currentPrices(options: SchemaOption[], 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;
}
const open = (o.earlyBirdTiers || []).filter((t) => now < new Date(t.deadline)).map((t) => t.price);
prices.push(open.length > 0 ? Math.min(...open) : o.price);
}
return prices.filter((p) => Number.isFinite(p));
}
export function eventJsonLd(
event: SchemaEvent,
{ pageUrl, imageUrl, organizerName, siteUrl }: { pageUrl: string; imageUrl: string | null; organizerName: string; siteUrl: string },
) {
const now = new Date();
const options = event.eventOptions || [];
const limited = options.filter((o) => (o.stockLimit ?? 0) > 0);
const soldOut = limited.length > 0 && limited.every((o) => o.availableCount !== undefined && o.availableCount <= 0);
// Contact-only events (requiresRegistration false) have no tickets to offer.
let offers: Record<string, unknown> | undefined;
if (event.requiresRegistration !== false) {
const prices = options.length > 0 ? currentPrices(options, now) : [0];
const low = Math.min(...prices);
const high = Math.max(...prices);
offers = {
"@type": low === high ? "Offer" : "AggregateOffer",
...(low === high ? { price: low.toFixed(2) } : { lowPrice: low.toFixed(2), highPrice: high.toFixed(2) }),
priceCurrency: "ZAR",
availability: soldOut ? "https://schema.org/SoldOut" : "https://schema.org/InStock",
url: `${siteUrl}/register/${event.id}`,
...(event.goLiveAt ? { validFrom: new Date(event.goLiveAt).toISOString() } : {}),
};
}
return {
"@context": "https://schema.org",
"@type": "Event",
name: event.title,
...(event.description ? { description: event.description.slice(0, 5000) } : {}),
startDate: new Date(event.startDate).toISOString(),
endDate: new Date(event.endDate).toISOString(),
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
...(event.location ? { location: { "@type": "Place", name: event.location, address: event.location } } : {}),
...(imageUrl ? { image: [imageUrl] } : {}),
url: pageUrl,
organizer: { "@type": "Organization", name: organizerName, url: siteUrl },
...(offers ? { offers } : {}),
};
}
/** JSON for a <script type="application/ld+json">, safe against "</script>" in event text. */
export function jsonLdString(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}
@@ -0,0 +1,39 @@
import type { CrosscodeEvent } from "@crosscode/contracts";
import { apiFetchListForPrerender } from "@/lib/api";
/**
* Events from the church's other products (2.4.0, Settings → Linked products → Show events from):
* read-only copies as `crosscode.event/1`, each with its own page here (/events/linked/…) that
* points search engines and visitors to the product it comes from.
*/
export type LinkedEvent = {
key: string;
product: "website" | "app";
productName: string;
event: CrosscodeEvent;
};
/** Upcoming linked events for a public page. Never fails the page: no events if the API can't answer. */
export async function fetchLinkedEvents(campus?: string): Promise<LinkedEvent[]> {
const query = campus ? `?campus=${encodeURIComponent(campus)}` : "";
try {
return await apiFetchListForPrerender<LinkedEvent>(`/api/v2/linked-events${query}`, { nextOptions: { next: { revalidate: 60 } } });
} catch {
return [];
}
}
/** This site's page for a linked event. */
export const linkedEventPath = (e: LinkedEvent) => `/events/linked/${e.product}/${e.event.id}`;
/** "From the Church Website". */
export const fromLabel = (e: LinkedEvent) => `From the ${e.productName}`;
/** Our events and linked ones in one list by start time. `startOf` gives our events' start. */
export function mergeByStart<T>(ours: T[], linked: LinkedEvent[], startOf: (e: T) => string): ({ kind: "own"; event: T } | { kind: "linked"; event: LinkedEvent })[] {
const all = [
...ours.map((event) => ({ kind: "own" as const, event, at: new Date(startOf(event)).getTime() })),
...linked.map((event) => ({ kind: "linked" as const, event, at: new Date(event.event.startsAt).getTime() })),
];
return all.sort((a, b) => a.at - b.at).map((x) => (x.kind === "own" ? { kind: "own" as const, event: x.event } : { kind: "linked" as const, event: x.event }));
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "2.2.0",
"version": "2.3.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+429
View File
@@ -0,0 +1,429 @@
# Cross Events 2.4.0 — protocol v2, Linked products, the event feed and `packages/seo`
Phase **2** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§4, §5 "Sibling discovery", §9, §11; decisions
5, 20). Written 2026-11-18. **Built 2026-11-18** on branches (contracts 1.4.0 and Events 2.4.0 on
`feat/events-2.4` here, Hub 2.2.0 on `feat/link-public-key`, crosscode-site on
`feat/linked-products`); not tagged yet. The decisions below were taken as proposed. Where the
build differs from this plan, see [Changes while building](#changes-while-building).
**What 2.4.0 is:** Cross Events becomes a full member of a church stack. It reports to the Hub as
`product: "events"` (protocol v2), shows the church's other products under **Settings → Linked
products** with a **Connect** button, **publishes** its public events as a `crosscode.event-feed/1`
feed, **shows** events from linked products, and builds its SEO data with the new shared
`packages/seo`. Nothing changes for a church that has only Cross Events, apart from a new
settings page that says "No other products yet".
The Website and App don't exist yet, so the "show events from" side is built and tested against
sample feeds (§8). It's ready for the Website (phase 4) without another Events release.
**Done when:**
- `events@2.4.0`, `contracts@1.4.0` and Hub `v2.2.0` are tagged and pushed.
- An Events install updated to 2.4.0 moves itself to protocol v2 with no admin action, and the
Hub shows it as v2 with a public key.
- The feed passes the contract (`parseEventFeed` with nothing rejected) for every event in the
e2e seed, and a sample Website feed shows up in Events with a canonical link to its origin.
- crosscode-site says "Works with the Church Website and App (coming)" on the Cross Events page
(ROADMAP §9, "Updating crosscode-site").
## Contents
1. [Before starting](#before-starting)
2. [Protocol v2](#1-protocol-v2)
3. [Linked products and Connect](#2-linked-products-and-connect)
4. [Publishing: the feed](#3-publishing-the-feed)
5. [Showing events from linked products](#4-showing-events-from-linked-products)
6. [`packages/seo`](#5-packagesseo)
7. [Settings, audit log and help](#6-settings-audit-log-and-help)
8. [What changes in each repo](#7-what-changes-in-each-repo)
9. [Testing](#8-testing)
10. [Releasing and rolling it out](#9-releasing-and-rolling-it-out)
11. [Changes while building](#changes-while-building)
12. [Decisions](#decisions)
13. [Still open](#still-open)
---
## Before starting
- **The rollout (ROLLOUT-1.0.md) is at least past step 1**, so production runs Hub 2.1.x. 2.4.0
needs Hub 2.2.0 (§1) and is released after it, but neither depends on the church servers
being adopted.
- `apps/events` builds and tests clean on `main` (`npm run check`), as the baseline.
- Events uses `@crosscode/contracts` as a workspace dependency for the first time (backend and
frontend). The backend is CommonJS with some TypeScript; the package ships both builds, so
`require('@crosscode/contracts')` works as it is.
## 1. Protocol v2
Today `src/hub/client.js` speaks protocol 1 (`PROTOCOL_VERSION = 1`). v2 is in
`@crosscode/contracts` (`hub.*`) and the Hub has accepted it since 2.0.0
([hub-protocol.md §6](./hub-protocol.md#6-protocol-version-2-hub-20)).
**The problem:** hub-protocol.md says an install moves to v2 by *registering again* with its
licence key and a public key. Events never stored the licence key (it's only sent once, from
`/setup` or "Connect to Hub"), so every church admin would have to find and retype it. The v2
heartbeat also has no way to send a public key.
**The fix (Hub 2.2.0, contracts 1.4.0):** the v2 heartbeat gets an optional `publicKey` (PEM).
The heartbeat is already signed with the install secret, so the Hub knows it's that install. The
Hub saves the key when the install has none, and refuses a *different* key
(`409 PUBLIC_KEY_MISMATCH`) unless Joshua clears it on the install's page (for a restored server
that lost its key). An optional field keeps the protocol at version 2 and the contract at `/1`
(ROADMAP §2, "Versioning").
What Events does:
| Step | Detail |
|------|--------|
| Key pair | On first start of 2.4.0, generate an Ed25519 key pair (`generateEd25519` from `@crosscode/contracts/signing`). Private key encrypted in `AppSetting` `hub_private_key` (same `encrypt` as the install secret), public key in `hub_public_key`. Both added to `HUB_KEYS`, so the generic settings endpoints never show them. Never regenerated unless missing |
| Heartbeat | `protocolVersion: 2`, `product: "events"`, `publicKey` until the Hub has acknowledged it (`hub_public_key_ack`), Events stats as in v1. Body checked with `hub.heartbeatRequestSchema` before sending (a bug shows in tests, not as a 400 in production) |
| Register | `/setup` and "Connect to Hub" register with v2 straight away (`product`, `install.publicKey`) |
| Reply | Reads `linkedProducts` (§2) and the licence's `customerId` / `product`; everything else as v1 |
| Falling back | If the Hub answers `400 UNSUPPORTED_PROTOCOL` (a Hub older than 2.0), send v1 and keep trying v2 once a day. Not expected in production; it keeps a restored old Hub from cutting installs off |
`hub-protocol.md` §6 "Moving an install to v2" is rewritten to describe this (both copies).
## 2. Linked products and Connect
**Settings → Linked products** (site admins only) lists the church's other installs from the
last heartbeat's `linkedProducts` (cached in `AppSetting` `hub_linked_products`, so a Hub outage
changes nothing; ROADMAP §5). For each: product name, address, and its state: **Not connected**
· **Connected** (since when, by whom) · **Connected, last sync failed** (when, why).
With Events only, the page says the church has no other Cross Code products yet, with a link to
crosscode.co.za.
### Connect
The Hub tells each install which siblings exist and their public keys. **Connect** turns that
into a working link: a shared secret for signed calls between the two, and the feed settings.
New contract: **`crosscode.link/1`** in `packages/contracts/src/link.ts`.
```
A (Events) B (e.g. Website)
admin clicks Connect
makes a 32-byte secret S
POST {B.url}/api/links/v1/connect ───────────────► 1. A is in B's own cached linkedProducts
{ (same Hub customer), by installId
schema: "crosscode.link/1", 2. the Ed25519 signature checks out against
type: "link.connect", the publicKey the Hub listed for A
from: { product, installId, url }, 3. `to.installId` is B; issuedAt within
to: { installId }, 5 minutes; nonce not seen before
secret: S, 4. stores S (encrypted), marks A connected
issuedAt, nonce, ◄── 200 { schema, type: "link.connected",
signature: <Ed25519 over the canonical JSON> from: {…B}, publicKey check, signature }
}
checks B's signed reply with B's Hub-listed key
stores S (encrypted), marks B connected
```
- **Trust comes from the Hub's list on both sides.** B accepts A only if A appears in *B's*
`linkedProducts` with that exact key, so only installs of the same church can link, and only
ones the Hub knows. The Hub is still not on the path at the time of the call (rule 2): both
sides use their cached lists.
- **No approval step on B.** Both installs belong to the same church; whoever is admin on either
side can connect. B's Linked products page shows "Connected by Cross Events on 18 Nov" and
either side can **Disconnect** (a signed `link.disconnect`; both drop the secret).
- **Connecting again** replaces the secret (e.g. after a restored backup lost it).
- After Connect, every call between the two (the `event.changed` webhook now, Accounts'
back-channel later) uses `LINK_HEADERS` HMAC with S, as `@crosscode/contracts/signing` already
defines.
- Errors are `crosscode.link/1` `{ message, code }`: `NOT_LINKED` (A isn't in B's list: "Wait for
the next Hub heartbeat, up to 15 minutes, or check the Hub"), `BAD_SIGNATURE`, `STALE_REQUEST`,
`REPLAYED`, `WRONG_INSTALL`.
- Key format: the Hub lists keys as PEM, while the agent helpers in `signing.ts` take raw
base64url. contracts 1.4.0 adds `ed25519PublicFromPem` / `signLink` / `verifyLink` so no
product converts by hand.
- Events also **answers** Connect, since a Website will usually be the one clicking it.
`POST /api/links/v1/connect` and `/disconnect` are public routes, rate-limited per IP, outside
`/api/v2` (they're a cross-product contract, like the feed).
Stored per link in a new table, not in `AppSetting`:
```prisma
model ProductLink {
installId String @id // the sibling's Hub install id
product String // website | app | accounts
url String
publicKey String // as listed by the Hub when connected
secret String // encrypted
connectedAt DateTime
connectedBy String? // a user id when connected here, null when the sibling did it
showEvents Boolean @default(false) // "Show events from" (§4)
lastSyncAt DateTime?
lastSyncError String?
lastGoodAt DateTime?
}
```
If a sibling disappears from `linkedProducts` (uninstalled, or the licence moved), the link stays
but shows **No longer listed by the Hub**. Its events keep showing until an admin removes the
link, so a Hub mistake can't empty the church's event list.
## 3. Publishing: the feed
`GET /api/feed/v1/events?updatedSince=<ISO>` → `crosscode.event-feed/1` (ROADMAP §4,
"Transport"). Public, no sign-in: it only carries what the public event pages already show. It
answers only when **Publish my events** is on (default **on**; otherwise `404 FEED_OFF`).
### Which events
The same rule as the public pages, `publicEventWhere()` in `src/utils/series.js`: `isActive`, not
`isHidden`, `goLiveAt` passed. Plus:
- Events that ended more than **30 days** ago are left out of a full fetch (no `updatedSince`).
An event that ends doesn't go into `deleted`: siblings keep their copy and drop it from
"upcoming" themselves.
- An event's campus goes out as `campus: { slug, name }`, `null` for all campuses.
- **Never** in the feed: kids check-in and volunteer options, contact name/phone/email (the
church's contact for an event can be a person), the attendee form, prices of staff-only options.
### `updatedAt` and `deleted` that are actually right
An event's public face changes without its row changing: it goes live when `goLiveAt` passes,
registration closes at the deadline, and it fills up as tickets sell. `Event.updatedAt` misses
all three, and Events never deletes an event (`deleteEvent` deactivates it). So the feed is kept
in a table of what was last published:
```prisma
model FeedEntry {
eventId String @id
hash String // sha256 of the canonical crosscode.event/1 payload
payload Json
changedAt DateTime // the event's `updatedAt` in the feed
removedAt DateTime? // set when it stops being public: goes into `deleted`
}
```
- A **`feed-refresh`** job (pg-boss, every 5 minutes, and queued straight after an event, option,
session or registration change through the existing Prisma extension in `config/db.js`) builds
each candidate event's `crosscode.event/1`, compares the hash and bumps `changedAt` only when
something a sibling would see has changed. An event that stopped being public gets `removedAt`.
- The feed answers from this table: `events` = rows with `changedAt > updatedSince` and no
`removedAt`; `deleted` = rows with `removedAt > updatedSince`. With no `updatedSince`, every row
without `removedAt`. Rows removed more than 90 days ago are cleaned up.
- When the job changes anything, it sends **`event.changed`** (`eventChangedSchema`, at most 100
ids) to every connected link, signed with that link's secret, using the retries and SSRF rules
of `utils/webhooks.js` (1 min, 5 min, 30 min, 2 h, then give up; the 15-minute poll catches up).
### Building `crosscode.event/1` from an Event
A new `src/feed/toCrosscodeEvent.ts`, checked against `eventSchema` in tests for every e2e seed
event:
| Field | From |
|-------|------|
| `id` | `Event.id` (already a UUID) |
| `origin` | `{ product: "events", installId: hub_install_id, url: <APP_URL>/events/<id> }` |
| `status` | `published` (Events has no "cancelled" state today: cancelling is deactivating, so it goes into `deleted`) |
| `summary` | `null` (no such field yet) |
| `description` | The plain-text description with markdown characters escaped, so it reads the same when rendered as markdown |
| `imageUrl` | `picture`, made absolute |
| `timezone` | The site timezone (`TIMEZONE`) |
| `startsAt` / `endsAt` / `allDay` / `sessions` | `utils/sessions.js` (already keeps start/end in step with the sessions); `allDay: false` |
| `location` | `{ name: location, address: null, onlineUrl: null }`, or `null` |
| `series` | `{ id, name }` |
| `tags` | `[]` (no tags in Events yet) |
| `registration` | `mode`: `origin` when `requiresRegistration`, else `contact`; `url` the event page; `status` from the same rules as the event page (`not_open` before go-live, `closed` after the deadline or late-join cut-off, `full` when every limited main option is sold out, `waitlist` when full with a waitlist); `priceFrom` = the lowest current public price (early-bird and variants as in `eventSchema.ts` today), `null` when free |
## 4. Showing events from linked products
Per connected link: **Show events from this product** (off by default; ROADMAP §4 "Show events
from"). When on:
- **Sync:** a `feed-sync` job per link every **15 minutes**, and straight away on a valid
`event.changed` (`POST /api/feed/v1/changed`, verified with `LINK_HEADERS` and that link's
secret). It fetches `?updatedSince=<lastGoodAt minus 5 minutes>`, 15 s timeout, parses with
`parseEventFeed` (rejected events are logged, never block the rest), and upserts into
`ImportedEvent`. One failing link never holds up another (separate jobs).
- **The last good copy stays.** A failed sync only sets `lastSyncError`; admins see "Last synced
2 hours ago" on Linked products and on the dashboard's event list.
- **Read-only**, keyed by `origin.product` + `id` (`eventKey`), and **never re-published**: the
feed only ever reads `Event`, so no loops (ROADMAP §4 rules).
- Turning **Show events from** off, or removing the link, deletes that link's imported events.
```prisma
model ImportedEvent {
key String @id // eventKey(): "<product>:<id>"
linkId String // ProductLink.installId
payload Json // the crosscode.event/1 as received
startsAt DateTime // copied out for sorting and "upcoming"
endsAt DateTime
campusSlug String?
updatedAt DateTime
@@index([linkId])
@@index([startsAt])
}
```
**Where they show:** on the public **Events** list, the home page's upcoming events and campus
pages (by `campus.slug`, when it matches one of Events' campuses; otherwise under all campuses),
mixed in by date, with a small "From the church website" label. Not in the dashboard's event
tools, reports, check-in or anything that registers people.
**Their page:** `/events/linked/<product>/<id>`: title, dates, sessions, place, image, the
description rendered as markdown with HTML off (`react-markdown`, new dependency), and one button
by `registration.mode`: **More details** / **Register** linking to the origin (`origin` /
`external`), or the contact instructions (`contact`). The page has
`<link rel="canonical">` to `origin.url` (ROADMAP §11, "Imported events"), is left out of
`sitemap.xml`, and has no `Event` JSON-LD (the origin's page carries it, so search engines see
one event).
## 5. `packages/seo`
A new workspace, `@crosscode/seo` (ROADMAP §11): the schema.org builders and meta helpers every
product will use, built on `@crosscode/contracts`. Pure functions, no framework, ESM + CJS like
contracts, its own Jest tests.
| Export | What |
|--------|------|
| `eventJsonLd(event: CrosscodeEvent, opts)` | `Event` JSON-LD from `crosscode.event/1`: `eventStatus` (`EventCancelled` for `cancelled`), attendance mode (`OnlineEventAttendanceMode` / `Mixed…` from `location.onlineUrl`), `Place` or `VirtualLocation`, `offers` from `registration` (`SoldOut` for `full`, `validFrom` from `opensAt`), sessions as `subEvent` |
| `churchJsonLd(church: Church)` | `Church` (a schema.org `Organization` subtype): name, logo, address, geo, phone, service times as `openingHoursSpecification`-style `Event` entries, `sameAs` social links. Used for the Website's home page later; Events uses it as the event `organizer` |
| `canonicalUrl(base, path)` | Drops tracking parameters (`src`, `utm_*`, `fbclid`, `gclid`) and the trailing slash rule in one place |
| `pageMeta({ title, description, … })` | Title length and description trimming rules (60 / 155 characters), used for the Website's warnings later |
**Events moves onto it:** `frontend/src/lib/eventSchema.ts` is replaced. The public event detail
answer gains `crosscodeEvent` (the same builder as the feed, §3), and the page calls
`eventJsonLd` with it. **Nothing gets worse for Google:** today's JSON-LD gives a price *range*
(`AggregateOffer` low–high); `crosscode.event/1` only has `priceFrom`. `eventJsonLd` takes an
optional `priceRange` for the origin's own page, so Events keeps sending the high price. A
snapshot test compares the old and new JSON-LD for each seed event; the only allowed
differences are additions (`subEvent`, `organizer` as a `Church`).
The `organizer` comes from a `crosscode.church/1` that Events builds from its own site settings
(name, logo, colours, contact email). Sharing that profile with siblings is not part of 2.4.0
(see [Still open](#still-open)).
## 6. Settings, audit log and help
- **Settings → Linked products** (new page): the list, Connect / Disconnect, **Show events
from**, last sync. **Settings → Site → Publish my events** (on by default) with one line on
what it shares ("Your public events, as they appear on your events page. Never anyone's
details.").
- **Audit log** (`utils/adminAudit.js`): `product_link_connected`, `product_link_disconnected`,
`feed_publish_toggled`, `feed_show_toggled`. Connections made by the sibling are logged with
no user.
- **Help:** a "Linked products" help article, and the setting descriptions. **What's new** for
2.4.0: "Ready for the Church Website and App: your events can show on them, and theirs here.
Nothing changes until you have them."
- **Readiness checks** (`utils/readiness.js`): warn when a link's last sync failed for more than
a day.
## 7. What changes in each repo
| Repo | Change | Version |
|------|--------|---------|
| `crosscode-platform` `packages/contracts` | `crosscode.link/1` (`link.ts`: connect, connected, disconnect, errors), optional `publicKey` on the v2 heartbeat, `ed25519PublicFromPem` / `signLink` / `verifyLink`, JSON Schema and samples for each | `contracts@1.4.0` |
| `crosscode-platform` `packages/seo` | New (§5) | Not tagged on its own: a workspace, versioned with its first user like `ui` |
| `crosscode-platform` `apps/events` | §1–§6. Migrations: `ProductLink`, `FeedEntry`, `ImportedEvent`. New deps: `@crosscode/contracts`, `@crosscode/seo` (workspace), `react-markdown` | `events@2.4.0` |
| `crosscode-platform` `docs/` | `hub-protocol.md` §6 (heartbeat `publicKey`, moving to v2), ROADMAP §9 phase 2 marked done, HANDOVER | — |
| `events-hub` | v2 heartbeat accepts and saves `publicKey` (`409 PUBLIC_KEY_MISMATCH` for a different one), **Clear public key** button on the install page (2FA again, audited), vendored `contracts-1.4.0.tgz`, its copy of `hub-protocol.md` | Hub `v2.2.0` |
| `crosscode-site` | "Works with the Church Website and App" on the Cross Events page, marked coming (`src/data/cross-events.mjs`) | `v1.4.0` |
New `.env` variables: **none planned.** If one turns up, it goes in all three templates
(HANDOVER, "Things to remember").
## 8. Testing
**Unit and integration (Jest, in `npm run check`):**
- contracts: `crosscode.link/1` samples parse; `signLink` / `verifyLink` refuse a changed body,
another key, a stale `issuedAt` and a replayed nonce.
- seo: `eventJsonLd` / `churchJsonLd` for every contract sample; the old-vs-new snapshot (§5).
- Events, Hub client: the v2 heartbeat body passes `hub.heartbeatRequestSchema`; the key pair is
made once; `publicKey` stops being sent after the ack; falling back to v1 on
`UNSUPPORTED_PROTOCOL`.
- Events, feed: every e2e seed event passes `eventSchema`; hidden, inactive, not-yet-live and
kids/volunteer data never appear; `updatedSince` returns exactly what changed, including
go-live, deadline and selling out with no `Event` row change; deactivating puts it in
`deleted`; feed off → `404 FEED_OFF`.
- Events, Connect: accepted from a listed sibling; refused when not listed, with a key other
than the listed one, stale, replayed or for another install; disconnect from either side.
- Events, sync: a sample Website feed with one invalid event (the rest import, the bad one is
logged); the source down (last copy kept, error shown); `event.changed` with a bad signature
refused; imported events never in our own feed.
- Hub (`events-hub`): v2 heartbeat with a key saves it; the same key is fine; a different one is
`409`; Clear lets a new one in.
**e2e (Playwright, `apps/events/e2e`):** a small fake "Website" (a fixture server in the e2e
setup serving `samples/event-feed.json` and answering Connect) to click through Linked products
→ Connect → Show events from → the imported event on `/events` → its page with the canonical link
and the origin's button; `sitemap.xml` doesn't list it. The §11 checks (title, description,
canonical, `og:image`, one `<h1>`, JSON-LD parses) on the event page and the imported event page.
**On the VM** (as in AGENT-1.0-PLAN §13), before tagging: two installs of Events can't be linked
(one per product per customer), so the VM run uses the fake Website from e2e as a second site
behind frp, against Hub 2.2.0. Check: an existing 2.3.x install updated through the agent moves
itself to v2 and appears with a key on the Hub; Connect works across the two servers; turning
the fake Website off keeps its events showing with "last synced".
## 9. Releasing and rolling it out
Order, each with its CHANGELOG entry and `npm run check` first:
1. `contracts@1.4.0` (platform), then the packed `.tgz` into `events-hub/backend/vendor/`.
2. Hub `v2.2.0`, deployed (`events-hub/deployment.md`).
3. `events@2.4.0` (its `WHATS-NEW.md` heading needs no `requires`: against a Hub before 2.2.0 it
still works, only Linked products stays empty).
4. crosscode-site `v1.4.0`, deployed.
5. Each church updated through the Hub (a scheduled update, ROLLOUT-1.0 §5).
## Changes while building
1. **A different public key never fails the heartbeat** (§1 said `409 PUBLIC_KEY_MISMATCH`): the
heartbeat also refreshes the licence, so failing it could lock a church out after 30 days. The
Hub keeps the saved key, answers `publicKeyStatus: "mismatch"` and opens an alert on the
install; the site keeps sending its key until it gets `saved` or `matches`, so it's saved
right after Joshua clears the old one. Events shows the mismatch on Linked products.
2. **Update requests and AI calls stay on protocol 1** (every Hub accepts them); only register and
heartbeat move to v2. A Hub that refuses a v2 body (`UNSUPPORTED_PROTOCOL` or
`INVALID_REQUEST`) gets the same heartbeat again as v1, and v1 is used for a day. The v2
health fills in what v1 could leave empty (`jobs`, `pendingMigrations`), and the body is
checked against the contract before it's sent.
3. **`event.changed` is tried once more after a minute, then left to the 15-minute poll** (§3
said the webhooks' 1 min … 12 h schedule): retrying longer than the poll interval adds nothing.
4. **The feed is also refreshed before it's served** when the last refresh is over a minute old,
so it's right even with the jobs switched off (e2e, `FEED_JOBS_ENABLED=false`).
5. **Imported events must come from that link's install** (`origin.installId` and `product`),
so one product can't publish events as another. Others are skipped and counted.
6. **JSON-LD**: `organizer` stays an `Organization` (the snapshot rule allowed only additions);
`Church` JSON-LD is in `@crosscode/seo` for the Website. The price range is now from main
tickets only (before, an add-on such as a T-shirt could set the lowest price). The description
goes in as plain text, not the feed's markdown-escaped copy.
7. **The deploy builds the shared packages**: `scripts/products/events.sh` installs and builds
`packages/contracts` and `packages/seo` before Events when the checkout's Events uses them
(an older tag still builds as before; `scripts/tests/events.bats`).
8. **`FEED_JOBS_ENABLED`** (optional, default `true`) switches the `feed` and `feed-sync` jobs,
like the other job flags (in `.env.example` and SETTINGS.md, not the env templates).
9. The readiness check is on the existing readiness page; contracts 1.4.0 also adds
`FEED_PATHS` and `typesVersions` (so `@crosscode/contracts/signing` has types under the
Events backend's `moduleResolution: node`).
10. **Not run yet:** the e2e spec (`e2e/linked-products.spec.ts`, needs the e2e Postgres) and the
VM test (§8): this machine has neither Postgres nor WSL. Both before tagging.
## Decisions
Proposed in this plan, to confirm before building:
1. **Moving to v2 needs no admin action:** the v2 heartbeat carries the install's public key
(optional field), instead of re-registering with the licence key (§1). Needs Hub 2.2.0.
2. **Connect needs no approval on the other side**, and trust comes from each side's own cached
Hub list (§2).
3. **Publish my events is on by default** (it only shares what the public pages already show);
**Show events from** is off by default per link.
4. **The feed is built from a `FeedEntry` table**, not straight from `Event`, so go-live,
deadlines and selling out are reported as changes (§3).
5. **Imported events get their own page** in Events with a canonical link to the origin, rather
than linking straight out from the list (§4).
6. Ended events stay out of `deleted`; a full fetch covers events that ended up to 30 days ago.
## Still open
- **Who owns the church profile (`crosscode.church/1`)** once there's more than one product?
Events builds one from its own settings for its JSON-LD in 2.4.0, but doesn't serve it to
siblings. The Website (phase 4) is the natural owner; decide before phase 4.
- **Event `summary` and `tags`** go out empty because Events has no such fields. Add them in a
later 2.x if the Website's event cards need them.
- **A "cancelled" state in Events** (shown as cancelled rather than disappearing) would map to
`status: "cancelled"`. Not in 2.4.0.
+10 -7
View File
@@ -1,6 +1,6 @@
# Handover — Cross Code, all products
Last updated: 2026-11-17. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
Last updated: 2026-11-18. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
decisions table near the end). This file says where each phase stands and what comes next.
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
@@ -24,22 +24,25 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)).
| Phase | What | State |
|-------|------|-------|
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04. Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
| 1 | Hub 2.0.x | **Released** (`v2.0.0` 2026-11-05, `v2.0.1` AI tokens and `v2.0.2` refunds / voiding refunded invoices, 2026-11-17). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first) |
| 1 | Hub 2.0.x | **Released** (`v2.0.0` 2026-11-05, `v2.0.1` AI tokens and `v2.0.2` refunds / voiding refunded invoices, 2026-11-17). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). Deploy straight to the latest 2.1.x (below) |
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released** 2026-11-17 (`events@2.2.0`, with AI use in tokens and the backend under `/api`). **VM tested 2026-11-17** (EVENTS-2.2-PLAN §6, all passing after fixes). **Not rolled out:** servers still run `hope-events` `v2.1.1` until each install is adopted |
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) |
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). **Not rolled out** |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
| 1c | Cross Events 2.3.x: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). **`events@2.3.1`** 2026-11-18: Next.js 16.4.6 (security advisories for 16.2.0–16.4.4), so roll out 2.3.1, not 2.3.0. crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) |
| 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Built** 2026-11-18 ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), decisions taken as proposed, "Changes while building" there): `feat/events-2.4` here, `feat/link-public-key` in events-hub, `feat/linked-products` in crosscode-site. Unit tests pass. **Not tagged:** the e2e spec and the VM test haven't run (no Postgres on the dev machine) |
| 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
## Next up
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md): Hub 2.1.0 (make and back up
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) (with the latest patch
releases: Hub 2.1.1, agent 1.0.1, Events 2.3.1): Hub 2.1 (make and back up
the job-signing key first) → the central server's agent (check `proxy_bind_addr = 127.0.0.1`)
→ each church server's agent → **adopt** the demo site, then each church (Link existing → Move
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
4. **Cross Events 2.4.0** (phase 2), as in ROADMAP §9.
4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events`
(with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its
order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0).
## The VM test (2026-11-17)
+1 -1
View File
@@ -616,7 +616,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. Planned with no feature changes; two small ones were added on 2026-11-17 (decided by Joshua): **AI use shown in tokens**, never rand, outside the Hub (needs Hub 2.0.1), and **everything the backend serves under `/api`**, so a site and its API share one address and one proxy rule. **Tagged 2026-11-17, before the VM testing; VM tested the same day** | Before more products, so every product is released and deployed the same way from the start |
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. **Released 2026-11-17** (`events@2.3.0`) | Independent and useful now; the Accounts migration later carries it over |
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.3.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). **Released 2026-11-17** after the VM test; rollout in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events | Small; ready for when the Website exists |
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists |
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one |
| 4 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case |
| 5 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide | Breaking change, so a major version, after Accounts is proven on the Website |
+21 -3
View File
@@ -332,6 +332,24 @@ what's needed) until the church's install of that product runs that version or l
**AI.** The monthly cap and markup are the church's, shared by all its installs: a call from any of
them counts what all of them used this month.
**Moving an install to v2** (e.g. Cross Events 2.4.0): register again with `protocolVersion: 2`,
the product and a public key (same licence and address: same install id, new secret), then send v2
heartbeats. Nothing on the Hub needs changing.
**Moving an install to v2** (e.g. Cross Events 2.4.0, Hub 2.2.0+): an install that registered with
v1 just starts sending v2 heartbeats, with its Ed25519 public key (PEM) in `publicKey`. It doesn't
need its licence key again (Cross Events never stored it). The heartbeat is already signed with the
install secret, so the Hub knows whose key it is. The reply says what happened in
`publicKeyStatus`:
| `publicKeyStatus` | Meaning |
|-------------------|---------|
| `saved` | The Hub had no key for the install and saved this one; the church's other installs list it from their next heartbeat |
| `matches` | The Hub already has this key (line endings and surrounding whitespace don't count) |
| `mismatch` | The Hub has a **different** key and keeps it: an alert opens on the install, and Joshua can **Clear public key** on its page (two-factor again) when the server was restored or rebuilt; the next heartbeat then saves the new key |
A key problem never fails the heartbeat: the licence keeps refreshing whatever happens to the key.
An install keeps sending `publicKey` until it gets `saved` or `matches`. A Hub before 2.2.0 ignores
the field (no `publicKeyStatus`), so the install isn't listed to its siblings until the Hub is
updated. Registering again with `protocolVersion: 2`, the product and a public key (same licence
and address: same install id, new secret) also works, as before.
**Connecting two installs** (Settings → Linked products → Connect) is between the installs, not
through the Hub: `crosscode.link/1` in `@crosscode/contracts` (`src/link.ts`), with each side
checking the other against the `linkedProducts` it has cached from the Hub.
+1244 -55
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -69,8 +69,8 @@
"@radix-ui/react-toast": "1.2.23",
"@radix-ui/react-tooltip": "1.2.16",
"autoprefixer": "10.5.4",
"eslint-config-next": "16.4.3",
"next": "16.4.3",
"eslint-config-next": "16.4.6",
"next": "16.4.6",
"postcss": "8.5.26",
"react-hook-form": "7.86.0",
"tailwind-merge": "3.6.0",
+7
View File
@@ -11,6 +11,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
@@ -62,6 +63,12 @@ for install → Hub; `LINK_HEADERS` (`X-Crosscode-Sender`, `-Timestamp`, `-Signa
`event.changed` webhooks and Accounts back-channel calls, with the secret set up by **Connect**.
Verify the raw bytes before parsing the JSON.
**Connect** (`crosscode.link/1`) is signed with each install's Ed25519 key instead: `signLink(message,
privateKeyPem)` and `verifyLink(message, senderPem)`, over the message without `signature` as
canonical JSON. The receiver takes the sender's PEM from its own cached `linkedProducts` (never
from the message) and refuses a nonce it has seen. `ed25519PublicToPem` / `ed25519PublicFromPem`
convert between the raw keys `generateEd25519` makes and the PEM the Hub lists.
### JSON Schema
`schemas/` has a JSON Schema (draft 2020-12) for every contract, for consumers that don't use
+8 -1
View File
@@ -1,12 +1,19 @@
{
"name": "@crosscode/contracts",
"version": "1.3.0",
"version": "1.4.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED",
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"signing": [
"./dist/signing.d.ts"
]
}
},
"exports": {
".": {
"import": {
@@ -36,5 +36,6 @@
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsQbIsjVsJY9k9jLjMSbscXdD9wONmLw90MrMHptfmSQ=\n-----END PUBLIC KEY-----\n"
}
],
"serverTime": "2026-11-03T10:15:00.120Z"
"serverTime": "2026-11-03T10:15:00.120Z",
"publicKeyStatus": "saved"
}
@@ -0,0 +1,16 @@
{
"schema": "crosscode.link/1",
"type": "link.connect",
"from": {
"product": "events",
"installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c",
"url": "https://events.hopefamily.co.za"
},
"to": {
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02"
},
"secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"issuedAt": "2026-11-20T10:00:00.000Z",
"nonce": "n0nce-AbCdEfGhIjKlMnOpQr",
"signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA"
}
@@ -0,0 +1,16 @@
{
"schema": "crosscode.link/1",
"type": "link.connected",
"from": {
"product": "website",
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02",
"url": "https://www.hopefamily.co.za"
},
"to": {
"installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c"
},
"inReplyTo": "n0nce-AbCdEfGhIjKlMnOpQr",
"issuedAt": "2026-11-20T10:00:00.400Z",
"nonce": "n0nce-ZyXwVuTsRqPoNmLkJi",
"signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA"
}
@@ -0,0 +1,15 @@
{
"schema": "crosscode.link/1",
"type": "link.disconnect",
"from": {
"product": "website",
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02",
"url": "https://www.hopefamily.co.za"
},
"to": {
"installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c"
},
"issuedAt": "2026-12-01T08:00:00.000Z",
"nonce": "n0nce-DiScOnNeCt0123456",
"signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA"
}
@@ -107,6 +107,10 @@
"pendingMigrations"
]
},
"publicKey": {
"type": "string",
"pattern": "^-----BEGIN PUBLIC KEY-----.*"
},
"product": {
"type": "string",
"const": "events"
@@ -430,6 +434,10 @@
"pendingMigrations"
]
},
"publicKey": {
"type": "string",
"pattern": "^-----BEGIN PUBLIC KEY-----.*"
},
"product": {
"type": "string",
"const": "website"
@@ -641,6 +649,10 @@
"pendingMigrations"
]
},
"publicKey": {
"type": "string",
"pattern": "^-----BEGIN PUBLIC KEY-----.*"
},
"product": {
"type": "string",
"const": "app"
@@ -840,6 +852,10 @@
"pendingMigrations"
]
},
"publicKey": {
"type": "string",
"pattern": "^-----BEGIN PUBLIC KEY-----.*"
},
"product": {
"type": "string",
"const": "accounts"
@@ -175,6 +175,14 @@
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"publicKeyStatus": {
"type": "string",
"enum": [
"saved",
"matches",
"mismatch"
]
}
},
"required": [
@@ -0,0 +1,84 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-connect.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.link/1"
},
"from": {
"type": "object",
"properties": {
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
},
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"product",
"installId",
"url"
]
},
"to": {
"type": "object",
"properties": {
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
},
"required": [
"installId"
]
},
"issuedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"nonce": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{22,64}$"
},
"signature": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{86}$"
},
"type": {
"type": "string",
"const": "link.connect"
},
"secret": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{43}$"
}
},
"required": [
"schema",
"from",
"to",
"issuedAt",
"nonce",
"signature",
"type",
"secret"
]
}
@@ -0,0 +1,84 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-connected.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.link/1"
},
"from": {
"type": "object",
"properties": {
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
},
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"product",
"installId",
"url"
]
},
"to": {
"type": "object",
"properties": {
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
},
"required": [
"installId"
]
},
"issuedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"nonce": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{22,64}$"
},
"signature": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{86}$"
},
"type": {
"type": "string",
"const": "link.connected"
},
"inReplyTo": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{22,64}$"
}
},
"required": [
"schema",
"from",
"to",
"issuedAt",
"nonce",
"signature",
"type",
"inReplyTo"
]
}
@@ -0,0 +1,79 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-disconnect.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.link/1"
},
"from": {
"type": "object",
"properties": {
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
},
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"product",
"installId",
"url"
]
},
"to": {
"type": "object",
"properties": {
"installId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
},
"required": [
"installId"
]
},
"issuedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"nonce": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{22,64}$"
},
"signature": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{86}$"
},
"type": {
"type": "string",
"const": "link.disconnect"
}
},
"required": [
"schema",
"from",
"to",
"issuedAt",
"nonce",
"signature",
"type"
]
}
@@ -0,0 +1,19 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-disconnected.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.link/1"
},
"type": {
"type": "string",
"const": "link.disconnected"
}
},
"required": [
"schema",
"type"
]
}
@@ -0,0 +1,26 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-error.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"message": {
"type": "string"
},
"code": {
"type": "string",
"enum": [
"NOT_LINKED",
"WRONG_INSTALL",
"BAD_SIGNATURE",
"STALE_REQUEST",
"REPLAYED",
"INVALID_REQUEST",
"LINKS_UNAVAILABLE"
]
}
},
"required": [
"message",
"code"
]
}
@@ -52,6 +52,11 @@ function contracts(c) {
"agent-job-config": c.agent.jobConfigSchema,
"env-template": c.agent.envTemplateSchema,
"church-export": c.churchExportSchema,
"link-connect": c.linkConnectSchema,
"link-connected": c.linkConnectedSchema,
"link-disconnect": c.linkDisconnectSchema,
"link-disconnected": c.linkDisconnectedSchema,
"link-error": c.linkErrorSchema,
};
}
+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;
+20 -1
View File
@@ -221,7 +221,18 @@ export const accountsStatsSchema = z.object({
linkedProducts: count,
});
const heartbeatBase = z.object({ protocolVersion, version: semverSchema, health: healthSchema });
const heartbeatBase = z.object({
protocolVersion,
version: semverSchema,
health: healthSchema,
/**
* The install's Ed25519 public key (PEM), contracts 1.4.0 / Hub 2.2.0. Lets an install that
* registered with protocol v1 move to v2 without its licence key (the heartbeat is already
* signed with the install secret). The Hub saves it when the install has none; see
* `publicKeyStatus` in the reply.
*/
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----").optional(),
});
export const heartbeatRequestSchema = z.discriminatedUnion("product", [
heartbeatBase.extend({ product: z.literal("events"), stats: eventsStatsSchema }),
@@ -231,6 +242,8 @@ export const heartbeatRequestSchema = z.discriminatedUnion("product", [
]);
export type HeartbeatRequest = z.infer<typeof heartbeatRequestSchema>;
export const PUBLIC_KEY_STATUSES = ["saved", "matches", "mismatch"] as const;
export const heartbeatResponseSchema = z.object({
licence: z.string(),
latestVersion: semverSchema.nullable(),
@@ -239,6 +252,12 @@ export const heartbeatResponseSchema = z.object({
/** The church's other installs. The install caches this, so a Hub outage changes nothing. */
linkedProducts: z.array(linkedProductSchema),
serverTime: dateTimeSchema,
/**
* Only when the heartbeat sent `publicKey` (Hub 2.2.0+): `saved` (the Hub had none),
* `matches`, or `mismatch` (the Hub has another key; it keeps its own and flags the install
* until Joshua clears it). Never a failed heartbeat: the licence keeps refreshing either way.
*/
publicKeyStatus: z.enum(PUBLIC_KEY_STATUSES).optional(),
});
export type HeartbeatResponse = z.infer<typeof heartbeatResponseSchema>;
+1
View File
@@ -8,6 +8,7 @@ export * from "./event";
export * from "./church";
export * from "./identity";
export * from "./return-to";
export * from "./link";
export * as hub from "./hub";
export * as agent from "./agent";
export * from "./church-export";
+73
View File
@@ -0,0 +1,73 @@
import { z } from "zod";
import { dateTimeSchema, idSchema, productSchema, urlSchema } from "./common";
import { schemaName } from "./schema-name";
/**
* `crosscode.link/1` — **Connect** under Settings → Linked products (docs/EVENTS-2.4-PLAN.md §2).
*
* The Hub tells each install which of its church's other installs exist and their Ed25519 public
* keys (`linkedProducts` in the heartbeat reply). Connect turns that into a working link between
* two of them: a shared secret for signed calls (`LINK_HEADERS` in `@crosscode/contracts/signing`:
* the `event.changed` webhook, later Accounts' back-channel calls).
*
* ```
* A → POST {B.url}/api/links/v1/connect link.connect (signed by A, carries the new secret)
* ← 200 link.connected (signed by B, echoes A's nonce)
* A → POST {B.url}/api/links/v1/disconnect link.disconnect (signed by A)
* ← 200 link.disconnected
* ```
*
* B accepts A only when A is in **B's own cached** `linkedProducts` with the key that signed the
* message, so only installs of the same church can link, and the Hub isn't on the path at the time
* of the call. Signatures are Ed25519 over the message without `signature`, as canonical JSON
* (`signLink` / `verifyLink`). Messages more than five minutes off the receiver's clock are
* refused, and a nonce is only accepted once.
*/
export const LINK_SCHEMA = schemaName("link", 1);
/** Where the endpoints live on every product, relative to its address. */
export const LINK_PATHS = { connect: "/api/links/v1/connect", disconnect: "/api/links/v1/disconnect" } as const;
export const LINK_ERROR_CODES = ["NOT_LINKED", "WRONG_INSTALL", "BAD_SIGNATURE", "STALE_REQUEST", "REPLAYED", "INVALID_REQUEST", "LINKS_UNAVAILABLE"] as const;
export const linkPartySchema = z.object({
product: productSchema,
installId: idSchema,
url: urlSchema,
});
export type LinkParty = z.infer<typeof linkPartySchema>;
/** 32 random bytes, base64url without padding. */
export const linkSecretSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "Expected 32 bytes, base64url");
const nonceSchema = z.string().regex(/^[A-Za-z0-9_-]{22,64}$/, "Expected a random base64url nonce");
const signatureSchema = z.string().regex(/^[A-Za-z0-9_-]{86}$/, "Expected an Ed25519 signature, base64url");
const signed = {
schema: z.literal(LINK_SCHEMA),
from: linkPartySchema,
to: z.object({ installId: idSchema }),
issuedAt: dateTimeSchema,
nonce: nonceSchema,
signature: signatureSchema,
};
/** A asks B to link, and hands it the secret both will sign calls with. */
export const linkConnectSchema = z.object({ ...signed, type: z.literal("link.connect"), secret: linkSecretSchema });
export type LinkConnect = z.infer<typeof linkConnectSchema>;
/** B's answer: signed by B and echoing A's nonce, so A knows the real B stored the secret. */
export const linkConnectedSchema = z.object({ ...signed, type: z.literal("link.connected"), inReplyTo: nonceSchema });
export type LinkConnected = z.infer<typeof linkConnectedSchema>;
/** Either side ends the link; both drop the secret. */
export const linkDisconnectSchema = z.object({ ...signed, type: z.literal("link.disconnect") });
export type LinkDisconnect = z.infer<typeof linkDisconnectSchema>;
export const linkDisconnectedSchema = z.object({ schema: z.literal(LINK_SCHEMA), type: z.literal("link.disconnected") });
export type LinkDisconnected = z.infer<typeof linkDisconnectedSchema>;
export const linkErrorSchema = z.object({ message: z.string(), code: z.enum(LINK_ERROR_CODES) });
export type LinkError = z.infer<typeof linkErrorSchema>;
export type LinkMessage = LinkConnect | LinkConnected | LinkDisconnect;
+49
View File
@@ -234,3 +234,52 @@ export function decryptExport(file: Uint8Array, key: string): Buffer {
decipher.setAuthTag(buf.subarray(buf.length - 16));
return Buffer.concat([decipher.update(buf.subarray(12, buf.length - 16)), decipher.final()]);
}
// ---------------------------------------------------------------------------------------------
// Product links (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2). The Hub lists each install's
// key as PEM (it's what register and the heartbeat send), so these take PEM.
// ---------------------------------------------------------------------------------------------
/** An install's Ed25519 public key as PEM (SPKI), from the raw key `generateEd25519` returns. */
export function ed25519PublicToPem(publicKey: string): string {
return okpPublic("Ed25519", publicKey).export({ format: "pem", type: "spki" }).toString();
}
/** The raw base64url key in an Ed25519 PEM. Throws for anything that isn't an Ed25519 public key. */
export function ed25519PublicFromPem(pem: string): string {
const key = createPublicKey(pem);
if (key.asymmetricKeyType !== "ed25519") throw new Error("Not an Ed25519 public key");
return rawPublic(key);
}
/** A fresh link secret: 32 random bytes, base64url. */
export function newLinkSecret(): string {
return b64u(randomBytes(32));
}
/** A fresh nonce for a link message. */
export function newLinkNonce(): string {
return b64u(randomBytes(18));
}
/** Sign a `crosscode.link/1` message (everything but `signature`, as canonical JSON). */
export function signLink<T extends Record<string, unknown>>(message: T, privateKeyPem: string): T & { signature: string } {
return { ...message, signature: ed25519Sign(privateKeyPem, jobSigningInput(message)) };
}
/**
* Check a `crosscode.link/1` message against the sender's PEM key as the receiver's Hub list has
* it, and its `issuedAt` against the clock. Replays (`nonce`) are the receiver's to track.
*/
export function verifyLink(message: Record<string, unknown>, publicKeyPem: string, opts: { now?: Date; maxSkewMs?: number } = {}): VerifyResult {
const issuedAt = typeof message.issuedAt === "string" ? Date.parse(message.issuedAt) : NaN;
const now = (opts.now ?? new Date()).getTime();
if (!Number.isFinite(issuedAt) || Math.abs(now - issuedAt) > (opts.maxSkewMs ?? MAX_CLOCK_SKEW_MS)) return { ok: false, code: "STALE_REQUEST" };
let raw: string;
try {
raw = ed25519PublicFromPem(publicKeyPem);
} catch {
return { ok: false, code: "BAD_SIGNATURE" };
}
return ed25519Verify(raw, jobSigningInput(message), message.signature) ? { ok: true } : { ok: false, code: "BAD_SIGNATURE" };
}
+65 -2
View File
@@ -1,5 +1,6 @@
import { createHmac } from "node:crypto";
import { hub } from "../src";
import { createHmac, generateKeyPairSync } from "node:crypto";
import { hub, linkConnectSchema, linkConnectedSchema } from "../src";
import * as s from "../src/signing";
import { HUB_HEADERS, LINK_HEADERS, sign, signedHeaders, verify } from "../src/signing";
import { sample } from "./helpers";
@@ -76,3 +77,65 @@ describe("signing", () => {
expect(verify({ secret, timestamp: "yesterday", signature: sign(secret, "yesterday", body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" });
});
});
describe("product links (crosscode.link/1)", () => {
const a = s.generateEd25519();
const b = s.generateEd25519();
const aPem = s.ed25519PublicToPem(a.publicKey);
const now = new Date("2026-11-20T10:00:00.000Z");
const connect = () =>
s.signLink(
{
schema: "crosscode.link/1",
type: "link.connect",
from: { product: "events", installId: "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c", url: "https://events.hopefamily.co.za" },
to: { installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02" },
secret: s.newLinkSecret(),
issuedAt: now.toISOString(),
nonce: s.newLinkNonce(),
},
a.privateKeyPem,
);
it("round-trips a key through PEM", () => {
expect(aPem.startsWith("-----BEGIN PUBLIC KEY-----")).toBe(true);
expect(s.ed25519PublicFromPem(aPem)).toBe(a.publicKey);
expect(() => s.ed25519PublicFromPem(generateKeyPairSync("x25519").publicKey.export({ format: "pem", type: "spki" }).toString())).toThrow();
});
it("signs a connect message that passes the schema and verifies with the sender's PEM", () => {
const msg = connect();
expect(linkConnectSchema.safeParse(msg).success).toBe(true);
expect(s.verifyLink(msg, aPem, { now })).toEqual({ ok: true });
});
it("refuses another key, a changed body and a stale message", () => {
const msg = connect();
expect(s.verifyLink(msg, s.ed25519PublicToPem(b.publicKey), { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
expect(s.verifyLink({ ...msg, secret: s.newLinkSecret() }, aPem, { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
expect(s.verifyLink({ ...msg, to: { installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e03" } }, aPem, { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
expect(s.verifyLink(msg, aPem, { now: new Date(now.getTime() + 6 * 60 * 1000) })).toEqual({ ok: false, code: "STALE_REQUEST" });
expect(s.verifyLink(msg, "not a key", { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
});
it("makes secrets and nonces the schema accepts", () => {
const reply = s.signLink(
{
schema: "crosscode.link/1",
type: "link.connected",
from: { product: "website", installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02", url: "https://www.hopefamily.co.za" },
to: { installId: "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c" },
inReplyTo: s.newLinkNonce(),
issuedAt: now.toISOString(),
nonce: s.newLinkNonce(),
},
b.privateKeyPem,
);
expect(linkConnectedSchema.safeParse(reply).success).toBe(true);
});
it("lets a heartbeat carry the install's public key", () => {
expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), publicKey: aPem }).success).toBe(true);
expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), publicKey: "nope" }).success).toBe(false);
});
});
@@ -36,6 +36,9 @@ const SAMPLE_SCHEMA: Record<string, string> = {
"hub-heartbeat-response.json": "hub-heartbeat-response",
"hub-licence-payload.json": "hub-licence-payload",
"church-export.json": "church-export",
"link-connect.json": "link-connect",
"link-connected.json": "link-connected",
"link-disconnect.json": "link-disconnect",
};
describe("JSON Schema (schemas/)", () => {
+6
View File
@@ -8,6 +8,9 @@ import {
eventFeedSchema,
eventSchema,
hub,
linkConnectSchema,
linkConnectedSchema,
linkDisconnectSchema,
identityClaimsSchema,
userDeletedReplySchema,
userExportReplySchema,
@@ -36,6 +39,9 @@ const SCHEMAS: Record<string, z.ZodType> = {
"hub-heartbeat-response.json": hub.heartbeatResponseSchema,
"hub-licence-payload.json": hub.licencePayloadSchema,
"church-export.json": churchExportSchema,
"link-connect.json": linkConnectSchema,
"link-connected.json": linkConnectedSchema,
"link-disconnect.json": linkDisconnectSchema,
};
describe("samples", () => {
+16
View File
@@ -0,0 +1,16 @@
# @crosscode/seo
The schema.org JSON-LD builders and meta helpers every public Cross Code site uses (ROADMAP-v3
§11), built on `@crosscode/contracts`. Events, the Church Website and the Church App produce the
same search data from the same `crosscode.event/1` and `crosscode.church/1`.
| Export | What |
|--------|------|
| `eventJsonLd(event, opts)` | `Event` from a `crosscode.event/1`: status, attendance mode, `Place` / `VirtualLocation`, `offers` from `registration` (a price range when the origin passes `priceRange`), sessions as `subEvent`. **Only the origin's page** carries it; an imported copy has a canonical link to the origin instead |
| `churchJsonLd(church, opts)` | `Church` from a `crosscode.church/1`: address, geo, phone, logo, service times, social links, campuses as `department` |
| `canonicalUrl(base, path)` | Absolute, without tracking parameters (`src`, `utm_*`, `fbclid`, …), `#…` or a trailing slash |
| `pageMeta({ title, description })` | Title and description as search engines show them (60 / 155 characters) and warnings for an editor |
| `jsonLdString(data)` | JSON for `<script type="application/ld+json">`, safe against `</script>` |
Pure functions, no framework. CommonJS and ESM like contracts. It's a workspace, versioned with
the apps that use it (it isn't tagged on its own).
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
testEnvironment: "node",
testMatch: ["<rootDir>/tests/**/*.test.ts"],
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
moduleFileExtensions: ["ts", "js", "json"],
modulePathIgnorePatterns: ["<rootDir>/dist/"],
};
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@crosscode/seo",
"version": "1.0.0",
"private": true,
"description": "schema.org JSON-LD and meta helpers every public Cross Code site uses, built on @crosscode/contracts (ROADMAP-v3 §11)",
"license": "UNLICENSED",
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./package.json": "./package.json"
},
"files": [
"dist",
"README.md"
],
"sideEffects": false,
"scripts": {
"build": "tsup",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "jest"
},
"dependencies": {
"@crosscode/contracts": "*"
}
}
+78
View File
@@ -0,0 +1,78 @@
import type { Address, Church } from "@crosscode/contracts";
/**
* schema.org `Church` JSON-LD (an `Organization` and a `Place`) from a `crosscode.church/1`, for
* a church's home and contact pages, so it shows up in local search and maps (ROADMAP-v3 §11).
*/
type JsonLd = Record<string, unknown>;
const DAYS: Record<string, string> = {
monday: "Monday",
tuesday: "Tuesday",
wednesday: "Wednesday",
thursday: "Thursday",
friday: "Friday",
saturday: "Saturday",
sunday: "Sunday",
};
function postalAddress(a: Address): JsonLd {
return {
"@type": "PostalAddress",
streetAddress: [a.line1, a.line2].filter(Boolean).join(", "),
...(a.suburb || a.city ? { addressLocality: a.suburb ? `${a.suburb}, ${a.city}` : a.city } : {}),
...(a.province ? { addressRegion: a.province } : {}),
...(a.postalCode ? { postalCode: a.postalCode } : {}),
addressCountry: a.country,
};
}
function geo(a: Address | null | undefined): JsonLd | undefined {
return a?.geo ? { "@type": "GeoCoordinates", latitude: a.geo.lat, longitude: a.geo.lng } : undefined;
}
export interface ChurchJsonLdOptions {
/** The page's own address (the church's home page by default: `links.website`). */
url?: string;
}
export function churchJsonLd(church: Church, opts: ChurchJsonLdOptions = {}): JsonLd {
// The church's main address: its contact address, else its only (or first) campus's.
const main = church.contact.address ?? church.campuses.find((c) => c.address)?.address ?? null;
const url = opts.url ?? church.links.website ?? church.links.events ?? undefined;
const mainGeo = geo(main);
const services = church.serviceTimes.filter((s) => !s.campus || church.campuses.length <= 1);
return {
"@context": "https://schema.org",
"@type": "Church",
name: church.name,
...(church.shortName ? { alternateName: church.shortName } : {}),
...(url ? { url } : {}),
...(church.branding.logoUrl ? { logo: church.branding.logoUrl, image: church.branding.logoUrl } : {}),
...(church.contact.email ? { email: church.contact.email } : {}),
...(church.contact.phone ? { telephone: church.contact.phone } : {}),
...(main ? { address: postalAddress(main) } : {}),
...(mainGeo ? { geo: mainGeo } : {}),
...(church.social.length > 0 ? { sameAs: church.social.map((s) => s.url) } : {}),
// Service times: when the doors are open, as Google reads it for a place.
...(services.length > 0
? { openingHoursSpecification: services.map((s) => ({ "@type": "OpeningHoursSpecification", dayOfWeek: `https://schema.org/${DAYS[s.day]}`, opens: s.time, ...(s.label ? { name: s.label } : {}) })) }
: {}),
// Several campuses: each one a place of its own.
...(church.campuses.length > 1
? {
department: church.campuses.map((c) => {
const g = geo(c.address);
return {
"@type": "Church",
name: `${church.name} ${c.name}`,
...(c.address ? { address: postalAddress(c.address) } : {}),
...(g ? { geo: g } : {}),
};
}),
}
: {}),
};
}
+114
View File
@@ -0,0 +1,114 @@
import type { CrosscodeEvent } from "@crosscode/contracts";
/**
* schema.org `Event` JSON-LD from a `crosscode.event/1`, the same for every product (ROADMAP-v3
* §11), so Google can show the event with its date, venue and ticket link. Checked with
* https://search.google.com/test/rich-results.
*
* Only the **origin** of an event puts this on its page. An imported copy has a canonical link to
* the origin instead and no JSON-LD, so search engines see one event, not one per product.
*/
export interface Organizer {
name: string;
url: string;
}
export interface EventJsonLdOptions {
/** The page this JSON-LD is on. Defaults to `event.origin.url`. */
pageUrl?: string;
/** The church (or the site's organisation) running the event. */
organizer?: Organizer;
/**
* The origin's own price range, in cents. `crosscode.event/1` only carries the lowest price,
* but the origin knows the highest too, and Google shows a range (`AggregateOffer`).
*/
priceRange?: { lowCents: number; highCents: number };
/** Where the ticket offer points. Defaults to `registration.url`. */
offerUrl?: string;
/** When tickets went (or go) on sale. Defaults to `registration.opensAt`. */
validFrom?: string | null;
}
type JsonLd = Record<string, unknown>;
const SCHEMA = "https://schema.org/";
const rand = (cents: number) => (cents / 100).toFixed(2);
function attendanceMode(event: CrosscodeEvent): string {
const online = Boolean(event.location?.onlineUrl);
const inPerson = Boolean(event.location?.name || event.location?.address);
if (online && inPerson) return `${SCHEMA}MixedEventAttendanceMode`;
if (online) return `${SCHEMA}OnlineEventAttendanceMode`;
return `${SCHEMA}OfflineEventAttendanceMode`;
}
function location(event: CrosscodeEvent): JsonLd | JsonLd[] | undefined {
const l = event.location;
if (!l) return undefined;
const places: JsonLd[] = [];
if (l.name || l.address) {
// Google wants an address; an event with only a place name uses the name for both.
places.push({ "@type": "Place", name: l.name ?? l.address, address: l.address ?? l.name });
}
if (l.onlineUrl) places.push({ "@type": "VirtualLocation", url: l.onlineUrl });
if (places.length === 0) return undefined;
return places.length === 1 ? places[0] : places;
}
function offers(event: CrosscodeEvent, opts: EventJsonLdOptions): JsonLd | undefined {
const r = event.registration;
// Contact-only and no-registration events have no tickets to offer.
if (r.mode === "contact" || r.mode === "none") return undefined;
// An external link without a price has nothing Google can show as an offer.
if (r.mode === "external" && !r.priceFrom && !opts.priceRange) return undefined;
const low = opts.priceRange?.lowCents ?? r.priceFrom?.amountCents ?? 0;
const high = opts.priceRange?.highCents ?? low;
const soldOut = r.status === "full" || r.status === "waitlist";
const validFrom = opts.validFrom === undefined ? r.opensAt : opts.validFrom;
const url = opts.offerUrl ?? r.url;
return {
"@type": low === high ? "Offer" : "AggregateOffer",
...(low === high ? { price: rand(low) } : { lowPrice: rand(low), highPrice: rand(high) }),
priceCurrency: r.priceFrom?.currency ?? "ZAR",
availability: soldOut ? `${SCHEMA}SoldOut` : `${SCHEMA}InStock`,
...(url ? { url } : {}),
...(validFrom ? { validFrom: new Date(validFrom).toISOString() } : {}),
};
}
export function eventJsonLd(event: CrosscodeEvent, opts: EventJsonLdOptions = {}): JsonLd {
const live = event.sessions.filter((s) => !s.cancelled);
const offer = offers(event, opts);
const place = location(event);
return {
"@context": "https://schema.org",
"@type": "Event",
name: event.title,
...(event.description ? { description: event.description.slice(0, 5000) } : event.summary ? { description: event.summary } : {}),
startDate: new Date(event.startsAt).toISOString(),
endDate: new Date(event.endsAt).toISOString(),
eventStatus: event.status === "cancelled" ? `${SCHEMA}EventCancelled` : `${SCHEMA}EventScheduled`,
eventAttendanceMode: attendanceMode(event),
...(place ? { location: place } : {}),
...(event.imageUrl ? { image: [event.imageUrl] } : {}),
url: opts.pageUrl ?? event.origin.url,
...(opts.organizer ? { organizer: { "@type": "Organization", name: opts.organizer.name, url: opts.organizer.url } } : {}),
...(offer ? { offers: offer } : {}),
// A multi-day event: each date as a sub-event, so Google can list the dates.
...(live.length > 1
? {
subEvent: live.map((s) => ({
"@type": "Event",
name: s.label ? `${event.title}: ${s.label}` : event.title,
startDate: new Date(s.startsAt).toISOString(),
endDate: new Date(s.endsAt).toISOString(),
...(s.location ? { location: { "@type": "Place", name: s.location, address: s.location } } : place ? { location: place } : {}),
})),
}
: {}),
};
}
+8
View File
@@ -0,0 +1,8 @@
/**
* @crosscode/seo — the schema.org JSON-LD builders and meta helpers every public Cross Code site
* uses (ROADMAP-v3 §11), built on `@crosscode/contracts` so Events, the Website and the App
* produce the same data from the same `crosscode.event/1` and `crosscode.church/1`.
*/
export * from "./event";
export * from "./church";
export * from "./meta";
+61
View File
@@ -0,0 +1,61 @@
/**
* Meta helpers every public Cross Code site uses (ROADMAP-v3 §11, "The baseline").
*/
/** Query parameters that only track where a visitor came from; never part of a canonical URL. */
const TRACKING = /^(utm_[a-z_]+|src|fbclid|gclid|gbraid|wbraid|msclkid|mc_cid|mc_eid|ref)$/i;
/**
* The canonical address of a page: absolute, without tracking parameters or a `#…`, and without
* a trailing slash (except the home page).
*/
export function canonicalUrl(base: string, path = "/"): string {
const url = new URL(path, base.endsWith("/") ? base : `${base}/`);
for (const key of [...url.searchParams.keys()]) if (TRACKING.test(key)) url.searchParams.delete(key);
url.hash = "";
if (url.pathname.length > 1) url.pathname = url.pathname.replace(/\/+$/, "");
url.searchParams.sort();
return url.toString();
}
export const TITLE_MAX = 60;
export const DESCRIPTION_MAX = 155;
/** Cuts text at a word boundary to `max` characters, with an ellipsis when it was cut. */
export function truncate(text: string, max: number): string {
const clean = text.replace(/\s+/g, " ").trim();
if (clean.length <= max) return clean;
const cut = clean.slice(0, max - 1);
const space = cut.lastIndexOf(" ");
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`;
}
export type MetaWarning = "title_missing" | "title_too_long" | "description_missing" | "description_too_long";
export interface PageMeta {
title: string;
description: string;
/** What an editor should fix (the Website's SEO panel shows these). */
warnings: MetaWarning[];
}
/** A page's title and description as search engines will show them, with warnings. */
export function pageMeta(input: { title?: string | null; description?: string | null; fallbackDescription?: string }): PageMeta {
const title = (input.title ?? "").replace(/\s+/g, " ").trim();
const raw = (input.description ?? "").trim();
const warnings: MetaWarning[] = [];
if (!title) warnings.push("title_missing");
else if (title.length > TITLE_MAX) warnings.push("title_too_long");
if (!raw) warnings.push("description_missing");
else if (raw.replace(/\s+/g, " ").length > DESCRIPTION_MAX) warnings.push("description_too_long");
return {
title,
description: truncate(raw || input.fallbackDescription || "", DESCRIPTION_MAX),
warnings,
};
}
/** JSON for a `<script type="application/ld+json">`, safe against `</script>` in the text. */
export function jsonLdString(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}
+141
View File
@@ -0,0 +1,141 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { churchSchema, eventSchema, type Church, type CrosscodeEvent } from "@crosscode/contracts";
import { canonicalUrl, churchJsonLd, eventJsonLd, jsonLdString, pageMeta, truncate } from "../src";
const SAMPLES = join(__dirname, "..", "..", "contracts", "samples");
const sample = <T>(file: string): T => JSON.parse(readFileSync(join(SAMPLES, file), "utf8")) as T;
const event = () => eventSchema.parse(sample("event.json")) as CrosscodeEvent;
const simple = () => eventSchema.parse(sample("event-simple.json")) as CrosscodeEvent;
const church = () => churchSchema.parse(sample("church.json")) as Church;
describe("eventJsonLd", () => {
it("builds an Event from crosscode.event/1", () => {
const ld = eventJsonLd(event(), { organizer: { name: "Hope Family Church", url: "https://events.hopefamily.co.za" } });
expect(ld).toMatchObject({
"@context": "https://schema.org",
"@type": "Event",
name: "Youth Camp 2027",
startDate: "2027-03-14T06:00:00.000Z",
endDate: "2027-03-16T12:00:00.000Z",
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
location: { "@type": "Place", name: "Camp Wartburg", address: "R103, Wartburg, KwaZulu-Natal" },
url: "https://events.hopefamily.co.za/events/youth-camp",
organizer: { "@type": "Organization", name: "Hope Family Church" },
offers: { "@type": "Offer", price: "450.00", priceCurrency: "ZAR", availability: "https://schema.org/InStock" },
});
expect((ld.subEvent as unknown[]).length).toBe(3);
});
it("gives a price range when the origin knows it", () => {
const ld = eventJsonLd(event(), { priceRange: { lowCents: 45000, highCents: 90000 } });
expect(ld.offers).toMatchObject({ "@type": "AggregateOffer", lowPrice: "450.00", highPrice: "900.00" });
});
it("marks full and waitlisted events sold out, and cancelled ones cancelled", () => {
const e = event();
e.registration.status = "full";
e.status = "cancelled";
const ld = eventJsonLd(e);
expect((ld.offers as Record<string, unknown>).availability).toBe("https://schema.org/SoldOut");
expect(ld.eventStatus).toBe("https://schema.org/EventCancelled");
});
it("has no offer for contact-only events, or for an external link without a price", () => {
const e = event();
e.registration = { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null };
expect(eventJsonLd(e).offers).toBeUndefined();
e.registration = { mode: "external", url: "https://example.org/tickets", status: "open", opensAt: null, closesAt: null, priceFrom: null };
expect(eventJsonLd(e).offers).toBeUndefined();
});
it("offers a free origin registration at 0.00", () => {
const e = event();
e.registration.priceFrom = null;
expect(eventJsonLd(e).offers).toMatchObject({ "@type": "Offer", price: "0.00" });
});
it("describes online and mixed events", () => {
const e = event();
e.location = { name: null, address: null, onlineUrl: "https://youtube.com/live/x" };
expect(eventJsonLd(e)).toMatchObject({ eventAttendanceMode: "https://schema.org/OnlineEventAttendanceMode", location: { "@type": "VirtualLocation" } });
e.location = { name: "Main hall", address: null, onlineUrl: "https://youtube.com/live/x" };
const ld = eventJsonLd(e);
expect(ld.eventAttendanceMode).toBe("https://schema.org/MixedEventAttendanceMode");
expect(ld.location).toEqual([
{ "@type": "Place", name: "Main hall", address: "Main hall" },
{ "@type": "VirtualLocation", url: "https://youtube.com/live/x" },
]);
});
it("works for a simple event from another product", () => {
const ld = eventJsonLd(simple());
expect(ld["@type"]).toBe("Event");
expect(ld.subEvent).toBeUndefined();
});
it("leaves cancelled sessions out of the dates", () => {
const e = event();
e.sessions[1]!.cancelled = true;
expect((eventJsonLd(e).subEvent as unknown[]).length).toBe(2);
});
});
describe("churchJsonLd", () => {
it("builds a Church with address, geo, service times and social links", () => {
const ld = churchJsonLd(church());
expect(ld).toMatchObject({
"@type": "Church",
name: "Hope Family Church",
alternateName: "Hope Family",
url: "https://www.hopefamily.co.za",
logo: "https://www.hopefamily.co.za/uploads/logo.png",
email: "office@hopefamily.co.za",
telephone: "+27161234567",
address: { "@type": "PostalAddress", streetAddress: "12 Church Street", addressLocality: "Meyerton Central, Meyerton", postalCode: "1961", addressCountry: "ZA" },
geo: { latitude: -26.5559, longitude: 28.0141 },
sameAs: ["https://www.facebook.com/hopefamilychurch", "https://www.youtube.com/@hopefamilychurch"],
});
expect((ld.openingHoursSpecification as unknown[]).length).toBe(2);
expect(ld.department).toBeUndefined();
});
it("lists each campus when there are several", () => {
const c = church();
c.campuses.push({ slug: "vereeniging", name: "Vereeniging", address: null });
const ld = churchJsonLd(c);
expect(ld.department).toEqual([
expect.objectContaining({ name: "Hope Family Church Meyerton" }),
{ "@type": "Church", name: "Hope Family Church Vereeniging" },
]);
});
});
describe("meta", () => {
it.each([
["https://e.co.za", "/events/1?src=whatsapp&utm_source=fb", "https://e.co.za/events/1"],
["https://e.co.za/", "/events/1/", "https://e.co.za/events/1"],
["https://e.co.za", "/", "https://e.co.za/"],
["https://e.co.za", "/events?campus=b&page=2&gclid=x#top", "https://e.co.za/events?campus=b&page=2"],
])("canonicalUrl(%s, %s)", (base, path, expected) => {
expect(canonicalUrl(base, path)).toBe(expected);
});
it("truncates at a word boundary", () => {
expect(truncate("Three days of worship, teaching and adventure", 30)).toBe("Three days of worship…");
expect(truncate("short", 30)).toBe("short");
});
it("warns about missing and long titles and descriptions", () => {
expect(pageMeta({ title: "", description: "" }).warnings).toEqual(["title_missing", "description_missing"]);
const long = pageMeta({ title: "x".repeat(61), description: "word ".repeat(40) });
expect(long.warnings).toEqual(["title_too_long", "description_too_long"]);
expect(long.description.length).toBeLessThanOrEqual(155);
expect(pageMeta({ title: "Home", description: null, fallbackDescription: "Hope Family Church" }).description).toBe("Hope Family Church");
});
it("makes JSON-LD safe inside a script tag", () => {
expect(jsonLdString({ name: "</script><script>alert(1)</script>" })).not.toContain("</script>");
});
});
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"types": ["node", "jest"]
},
"include": ["src", "tests", "tsup.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from "tsup";
// CommonJS for the Events backend, ESM for the Next.js apps, types for both (as contracts).
export default defineConfig({
entry: ["src/index.ts"],
format: ["cjs", "esm"],
dts: true,
sourcemap: true,
clean: true,
target: "es2022",
external: ["@crosscode/contracts"],
outExtension: ({ format }) => ({ js: format === "esm" ? ".mjs" : ".js" }),
});
+24 -3
View File
@@ -31,10 +31,27 @@ events_backup() {
.catch(e => { console.error(" Backup failed: " + e.message); process.exit(1); });'
}
# Only this app's workspaces, never the other products'. --include=dev: the TypeScript and Next
# builds need type and build packages even where NODE_ENV=production.
# The shared packages this checkout's Events uses (from 2.4.0: contracts and seo), built before it.
# Only the ones in the checkout, so going back to an older tag still installs and builds.
events_shared_packages() {
local p
for p in packages/contracts packages/seo; do
if [ -f "$1/$p/package.json" ] && grep -q "\"@crosscode/${p#packages/}\"" "$1/apps/events/backend/package.json" "$1/apps/events/frontend/package.json" 2>/dev/null; then
printf '%s\n' "$p"
fi
done
}
# Only this app's workspaces (and the shared packages it uses), never the other products'.
# --include=dev: the TypeScript and Next builds need type and build packages even where
# NODE_ENV=production; --include-workspace-root for the packages' build tool (tsup).
events_install_deps() {
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend
local -a shared=() ws=()
local p
mapfile -t shared < <(events_shared_packages "$1")
for p in "${shared[@]}"; do ws+=(-w "$p"); done
if [ "${#shared[@]}" -gt 0 ]; then ws+=(--include-workspace-root); fi
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund "${ws[@]}" -w apps/events/backend -w apps/events/frontend
}
events_migrate() {
@@ -47,6 +64,10 @@ events_pending_migrations() {
}
events_build() {
local p
while IFS= read -r p; do
run_as "$2" "$1/$p" npm run build || return 1
done < <(events_shared_packages "$1")
run_as "$2" "$(events_app "$1")/backend" npm run build &&
run_as "$2" "$(events_app "$1")/frontend" npm run build
}
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bats
# Cross Events' hooks that don't need a server: which shared packages a checkout builds first
# (contracts and seo from 2.4.0), and that an older checkout (2.3.x) builds without them.
# Run with `npm run test:scripts`.
setup() {
# shellcheck source=../products/events.sh
source "$BATS_TEST_DIRNAME/../products/events.sh"
TMP="$BATS_TEST_TMPDIR"
CALLS="$TMP/calls"
: > "$CALLS"
# Record what would run, as the app user, instead of running it.
run_as() { local user="$1" dir="$2"; shift 2; echo "$user|${dir#"$TMP"/}|$*" >> "$CALLS"; }
}
checkout() {
local dir="$TMP/$1"; shift
mkdir -p "$dir/apps/events/backend" "$dir/apps/events/frontend" "$dir/packages/contracts" "$dir/packages/seo"
echo '{"name":"@crosscode/contracts"}' > "$dir/packages/contracts/package.json"
echo '{"name":"@crosscode/seo"}' > "$dir/packages/seo/package.json"
printf '{"dependencies":{%s}}' "$1" > "$dir/apps/events/backend/package.json"
printf '{"dependencies":{%s}}' "$2" > "$dir/apps/events/frontend/package.json"
}
@test "2.4.0: contracts and seo are installed and built before Events" {
checkout new '"@crosscode/contracts":"*"' '"@crosscode/contracts":"*","@crosscode/seo":"*"'
run events_shared_packages "$TMP/new"
[ "$output" = $'packages/contracts\npackages/seo' ]
events_install_deps "$TMP/new" hope
grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund -w packages/contracts -w packages/seo --include-workspace-root -w apps/events/backend -w apps/events/frontend' "$CALLS"
: > "$CALLS"
events_build "$TMP/new" hope
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/seo new/apps/events/backend new/apps/events/frontend " ]
}
@test "2.3.x (no shared packages used): installed and built as before" {
checkout old '' ''
run events_shared_packages "$TMP/old"
[ -z "$output" ]
events_install_deps "$TMP/old" hope
grep -qx 'hope|old|npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend' "$CALLS"
: > "$CALLS"
events_build "$TMP/old" hope
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "old/apps/events/backend old/apps/events/frontend " ]
}
@test "a failing package build stops before Events is built" {
checkout new '"@crosscode/contracts":"*"' ''
run_as() { echo "${2#"$TMP"/}" >> "$CALLS"; [[ "$2" != */packages/contracts ]]; }
run events_build "$TMP/new" hope
[ "$status" -ne 0 ]
[ "$(cat "$CALLS")" = "new/packages/contracts" ]
}