diff --git a/CHANGELOG.md b/CHANGELOG.md index f845542..a963621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,33 @@ 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 diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 3405524..eec4252 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,47 @@ 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//` + (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 diff --git a/apps/events/SETTINGS.md b/apps/events/SETTINGS.md index e2f8693..a1b33cd 100644 --- a/apps/events/SETTINGS.md +++ b/apps/events/SETTINGS.md @@ -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. | diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index c8f4b7f..6230187 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,16 @@ 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 diff --git a/apps/events/backend/.env.example b/apps/events/backend/.env.example index f57ecd7..23b38fc 100644 --- a/apps/events/backend/.env.example +++ b/apps/events/backend/.env.example @@ -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 diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index 0af61d1..0d20e55 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -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", diff --git a/apps/events/backend/prisma/migrations/20261120120000_linked_products/migration.sql b/apps/events/backend/prisma/migrations/20261120120000_linked_products/migration.sql new file mode 100644 index 0000000..3ac868f --- /dev/null +++ b/apps/events/backend/prisma/migrations/20261120120000_linked_products/migration.sql @@ -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; diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index b9bc35a..ba83138 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -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(): ":" + 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]) +} diff --git a/apps/events/backend/src/app.js b/apps/events/backend/src/app.js index 451f429..66d5326 100644 --- a/apps/events/backend/src/app.js +++ b/apps/events/backend/src/app.js @@ -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()); diff --git a/apps/events/backend/src/config/db.js b/apps/events/backend/src/config/db.js index 4d25cdb..2162a60 100644 --- a/apps/events/backend/src/config/db.js +++ b/apps/events/backend/src/config/db.js @@ -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(); diff --git a/apps/events/backend/src/feed/build.ts b/apps/events/backend/src/feed/build.ts new file mode 100644 index 0000000..d000f69 --- /dev/null +++ b/apps/events/backend/src/feed/build.ts @@ -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(sessions: S[]): S[]; + registrationClosesAt(event: object, sessions: object[]): Date; + isPickOption(event: object, option: object): boolean; +}; +const { publicOptions } = require('../utils/volunteers') as { publicOptions(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; + +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(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 { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { takenCount } = require('../utils/stock') as { takenCount(where: object): Promise }; + const out: Availability = new Map(); + for (const o of publicOptions(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 { + /* 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)); +} diff --git a/apps/events/backend/src/feed/context.ts b/apps/events/backend/src/feed/context.ts new file mode 100644 index 0000000..51ae639 --- /dev/null +++ b/apps/events/backend/src/feed/context.ts @@ -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 }; +const { campusesEnabled } = require('../utils/campuses') as { campusesEnabled(): Promise }; +/* 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 { + 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 { + 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 { + 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 { + 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, + }; +} diff --git a/apps/events/backend/src/feed/entries.ts b/apps/events/backend/src/feed/entries.ts new file mode 100644 index 0000000..3aab87c --- /dev/null +++ b/apps/events/backend/src/feed/entries.ts @@ -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 | null = null; + +export async function refreshFeed(now = new Date(), db = prisma): Promise { + 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(); + + 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( + (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 { + 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 { + 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?.(); +} diff --git a/apps/events/backend/src/feed/notify.ts b/apps/events/backend/src/feed/notify.ts new file mode 100644 index 0000000..4bd187a --- /dev/null +++ b/apps/events/backend/src/feed/notify.ts @@ -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 { + 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 { + const result = await refreshOnce(now); + const { told } = await notifyLinks([...result.changed, ...result.removed]); + return { ...result, told }; +} diff --git a/apps/events/backend/src/feed/sync.ts b/apps/events/backend/src/feed/sync.ts new file mode 100644 index 0000000..f6b64b5 --- /dev/null +++ b/apps/events/backend/src/feed/sync.ts @@ -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 { + 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 { + const link: Link | null = await prisma.productLink.findUnique({ where: { installId } }); + if (!link) return { skipped: 'no such link' }; + return syncLink(link); +} diff --git a/apps/events/backend/src/hub/client.js b/apps/events/backend/src/hub/client.js index ce5ff3b..328551f 100644 --- a/apps/events/backend/src/hub/client.js +++ b/apps/events/backend/src/hub/client.js @@ -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 }; diff --git a/apps/events/backend/src/jobs/index.js b/apps/events/backend/src/jobs/index.js index f126cf5..6cc7056 100644 --- a/apps/events/backend/src/jobs/index.js +++ b/apps/events/backend/src/jobs/index.js @@ -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) { diff --git a/apps/events/backend/src/links/connect.ts b/apps/events/backend/src/links/connect.ts new file mode 100644 index 0000000..ad600b0 --- /dev/null +++ b/apps/events/backend/src/links/connect.ts @@ -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 }; +/* 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 { + 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 { + 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>({ + 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, 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 { + 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, 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>({ + 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>({ + 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 { + 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, 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' }); +} diff --git a/apps/events/backend/src/links/http.ts b/apps/events/backend/src/links/http.ts new file mode 100644 index 0000000..364f526 --- /dev/null +++ b/apps/events/backend/src/links/http.ts @@ -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 }; +/* 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 = {}): Promise { + 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 { + 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 }): Promise { + 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; +} diff --git a/apps/events/backend/src/links/routes.ts b/apps/events/backend/src/links/routes.ts new file mode 100644 index 0000000..2a5f4aa --- /dev/null +++ b/apps/events/backend/src/links/routes.ts @@ -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 }; +/* 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; +} diff --git a/apps/events/backend/src/links/store.ts b/apps/events/backend/src/links/store.ts new file mode 100644 index 0000000..bf90215 --- /dev/null +++ b/apps/events/backend/src/links/store.ts @@ -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 { + const row = await prisma.appSetting.findUnique({ where: { key } }); + return row?.value ?? null; +} + +async function write(key: string, value: string | null): Promise { + 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 { + return read('hub_public_key_status'); +} + +export async function setPublicKeyStatus(status: string | null): Promise { + 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 { + 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 { + 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 { + return (await linkedProducts()).find((l) => l.installId === installId) ?? null; +} diff --git a/apps/events/backend/src/utils/readiness.js b/apps/events/backend/src/utils/readiness.js index dc48056..66d0b15 100644 --- a/apps/events/backend/src/utils/readiness.js +++ b/apps/events/backend/src/utils/readiness.js @@ -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 }; diff --git a/apps/events/backend/src/v2/index.ts b/apps/events/backend/src/v2/index.ts index 8fa197a..31731f8 100644 --- a/apps/events/backend/src/v2/index.ts +++ b/apps/events/backend/src/v2/index.ts @@ -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 }; diff --git a/apps/events/backend/src/v2/resources/eventDetails.ts b/apps/events/backend/src/v2/resources/eventDetails.ts index cb2bf77..25d328e 100644 --- a/apps/events/backend/src/v2/resources/eventDetails.ts +++ b/apps/events/backend/src/v2/resources/eventDetails.ts @@ -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 } }; }, }); diff --git a/apps/events/backend/src/v2/resources/linkedProducts.ts b/apps/events/backend/src/v2/resources/linkedProducts.ts new file mode 100644 index 0000000..4af19c6 --- /dev/null +++ b/apps/events/backend/src/v2/resources/linkedProducts.ts @@ -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 }; +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 = { 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, + hubInstallId(), + publishOn(), + publicKeyStatus(), + ]); + const people = new Map( + (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('":", unique across products'), + product: z.string(), + productName: z.string(), + event: crosscodeEvent, +}); + +type ImportedRow = { key: string; payload: { origin: { product: string } } & Record; 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 }); + +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((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) } }; + }, +}); diff --git a/apps/events/backend/tests/hubConnectFromEnv.test.js b/apps/events/backend/tests/hubConnectFromEnv.test.js index e8891c8..a1b9d57 100644 --- a/apps/events/backend/tests/hubConnectFromEnv.test.js +++ b/apps/events/backend/tests/hubConnectFromEnv.test.js @@ -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); }), }, diff --git a/apps/events/backend/tests/linkedProducts.test.js b/apps/events/backend/tests/linkedProducts.test.js new file mode 100644 index 0000000..28e2a7f --- /dev/null +++ b/apps/events/backend/tests/linkedProducts.test.js @@ -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() }, + }); + }); +}); diff --git a/apps/events/backend/tests/support/fakeFeedDb.js b/apps/events/backend/tests/support/fakeFeedDb.js new file mode 100644 index 0000000..3097d9f --- /dev/null +++ b/apps/events/backend/tests/support/fakeFeedDb.js @@ -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; diff --git a/apps/events/docs/HANDOVER.md b/apps/events/docs/HANDOVER.md index 8a83d62..9230d5c 100644 --- a/apps/events/docs/HANDOVER.md +++ b/apps/events/docs/HANDOVER.md @@ -145,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/` → commit → bump with diff --git a/apps/events/e2e/linked-products.spec.ts b/apps/events/e2e/linked-products.spec.ts new file mode 100644 index 0000000..c321e48 --- /dev/null +++ b/apps/events/e2e/linked-products.spec.ts @@ -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>(text: string, values: unknown[] = []): Promise { + 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\nNo 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[] = []; + + 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(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); + }); +}); diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 64a1a9d..1ed2095 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -10,6 +10,8 @@ "api:types": "openapi-typescript src/lib/api-v2/openapi.json -o src/lib/api-v2/schema.d.ts" }, "dependencies": { + "@crosscode/contracts": "*", + "@crosscode/seo": "*", "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", "@radix-ui/react-accordion": "^1.2.11", @@ -42,6 +44,7 @@ "react-day-picker": "^9.8.1", "react-dom": "^19.3.1", "react-hook-form": "^7.62.0", + "react-markdown": "^10.1.0", "react-webcam": "^7.2.0", "tailwind-merge": "^3.3.1", "tailwindcss-animate": "^1.0.7", diff --git a/apps/events/frontend/src/app/campus/[slug]/page.tsx b/apps/events/frontend/src/app/campus/[slug]/page.tsx index e4026e0..27dea19 100644 --- a/apps/events/frontend/src/app/campus/[slug]/page.tsx +++ b/apps/events/frontend/src/app/campus/[slug]/page.tsx @@ -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(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }); + const [events, linked] = await Promise.all([ + apiFetchListForPrerender(`/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 (
@@ -79,14 +85,16 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s

Upcoming events

Events at {campus.name}, and church-wide events for every campus.

- {upcoming.length === 0 ? ( + {items.length === 0 ? (

No upcoming events at {campus.name} right now — check back soon.

) : (
- {upcoming.map(event => )} + {items.map(item => item.kind === "own" + ? + : )}
)} diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index bd7aac9..b490095 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -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" && } {activeTab === "webhooks" && } + {activeTab === "linked" && } {activeTab === "jobs" && } {activeTab === "licence" && } {activeTab === "ai" && } diff --git a/apps/events/frontend/src/app/events/[id]/page.tsx b/apps/events/frontend/src/app/events/[id]/page.tsx index 1e459e1..3afc649 100644 --- a/apps/events/frontend/src/app/events/[id]/page.tsx +++ b/apps/events/frontend/src/app/events/[id]/page.tsx @@ -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 (
- " in event text. */ -export function jsonLdString(data: unknown): string { - return JSON.stringify(data).replace(/ { + const query = campus ? `?campus=${encodeURIComponent(campus)}` : ""; + try { + return await apiFetchListForPrerender(`/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(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 })); +} diff --git a/docs/EVENTS-2.4-PLAN.md b/docs/EVENTS-2.4-PLAN.md index d637c0c..bfbc360 100644 --- a/docs/EVENTS-2.4-PLAN.md +++ b/docs/EVENTS-2.4-PLAN.md @@ -1,7 +1,10 @@ # 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. **Not started.** +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 @@ -35,8 +38,9 @@ sample feeds (§8). It's ready for the Website (phase 4) without another Events 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. [Decisions](#decisions) -12. [Still open](#still-open) +11. [Changes while building](#changes-while-building) +12. [Decisions](#decisions) +13. [Still open](#still-open) --- @@ -365,6 +369,39 @@ Order, each with its CHANGELOG entry and `npm run check` first: 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: diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index fa39f04..80ffbc9 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -28,7 +28,7 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). | 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.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) | **Planned** 2026-11-18: [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), with six decisions to confirm before building. Events keeps speaking protocol 1 until then | +| 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 @@ -40,10 +40,9 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). 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): confirm the decisions in - [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), then build it in its order (contracts 1.4.0 → - Hub 2.2.0 → Events 2.4.0 → crosscode-site 1.4.0). It can be built during the rollout; releasing - it needs Hub 2.2.0 deployed. +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) diff --git a/docs/ROADMAP-v3.md b/docs/ROADMAP-v3.md index ced4adf..545a42a 100644 --- a/docs/ROADMAP-v3.md +++ b/docs/ROADMAP-v3.md @@ -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. **Planned 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) | 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 | diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index 0fa23f9..ccc12e6 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -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. diff --git a/package-lock.json b/package-lock.json index 04168b8..1c0ab05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -63,6 +63,7 @@ "hasInstallScript": true, "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", @@ -89,6 +90,7 @@ "zod": "^4.6.7" }, "devDependencies": { + "@crosscode/seo": "*", "@types/express": "^5.0.6", "@types/jest": "^30.0.0", "@types/jsonwebtoken": "^9.0.10", @@ -108,6 +110,8 @@ "name": "@crosscode/events-frontend", "version": "2.3.1", "dependencies": { + "@crosscode/contracts": "*", + "@crosscode/seo": "*", "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", "@radix-ui/react-accordion": "^1.2.11", @@ -140,6 +144,7 @@ "react-day-picker": "^9.8.1", "react-dom": "^19.3.1", "react-hook-form": "^7.62.0", + "react-markdown": "^10.1.0", "react-webcam": "^7.2.0", "tailwind-merge": "^3.3.1", "tailwindcss-animate": "^1.0.7", @@ -911,6 +916,10 @@ "resolved": "apps/events/frontend", "link": true }, + "node_modules/@crosscode/seo": { + "resolved": "packages/seo", + "link": true + }, "node_modules/@crosscode/ui": { "resolved": "packages/ui", "link": true @@ -6779,6 +6788,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, "node_modules/@types/esrecurse": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", @@ -6792,6 +6810,15 @@ "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", "license": "MIT" }, + "node_modules/@types/estree-jsx": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz", + "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, "node_modules/@types/express": { "version": "5.0.6", "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", @@ -6824,6 +6851,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -6900,6 +6936,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -6911,7 +6956,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", - "dev": true, "license": "MIT" }, "node_modules/@types/node": { @@ -6962,7 +7006,6 @@ "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "devOptional": true, "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -7037,6 +7080,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, "node_modules/@types/yargs": { "version": "17.0.35", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", @@ -7301,7 +7350,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", - "dev": true, "license": "ISC" }, "node_modules/@unrs/resolver-binding-android-arm-eabi": { @@ -8664,6 +8712,16 @@ "@babel/core": "^7.11.0 || ^8.0.0-beta.1 || ^8.0.0" } }, + "node_modules/bail": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", + "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/balanced-match": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", @@ -9274,6 +9332,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -9308,6 +9376,46 @@ "node": ">=10" } }, + "node_modules/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-reference-invalid": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz", + "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chokidar": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", @@ -9469,6 +9577,16 @@ "node": ">= 0.8" } }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/commander": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", @@ -9693,7 +9811,6 @@ "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "devOptional": true, "license": "MIT" }, "node_modules/d3-array": { @@ -9937,6 +10054,19 @@ "node": ">=0.10.0" } }, + "node_modules/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/decompress": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/decompress/-/decompress-4.2.1.tgz", @@ -10280,6 +10410,15 @@ "node": ">= 0.8" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/destr": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", @@ -10320,6 +10459,19 @@ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", "license": "MIT" }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/dezalgo": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", @@ -11273,6 +11425,16 @@ "node": ">=4.0" } }, + "node_modules/estree-util-is-identifier-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", + "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", @@ -11439,6 +11601,12 @@ "devOptional": true, "license": "MIT" }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, "node_modules/fast-check": { "version": "3.23.2", "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", @@ -12418,6 +12586,46 @@ "node": ">= 0.4" } }, + "node_modules/hast-util-to-jsx-runtime": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz", + "integrity": "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-object": "^2.0.0", + "unist-util-position": "^5.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hermes-estree": { "version": "0.25.1", "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", @@ -12449,6 +12657,16 @@ "dev": true, "license": "MIT" }, + "node_modules/html-url-attributes": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", + "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -12652,6 +12870,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/inline-style-parser": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", + "license": "MIT" + }, "node_modules/internal-slot": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", @@ -12695,6 +12919,30 @@ "node": ">= 0.10" } }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/is-array-buffer": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", @@ -12871,6 +13119,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/is-document.all": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz", @@ -12963,6 +13221,16 @@ "node": ">=0.10.0" } }, + "node_modules/is-hexadecimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz", + "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/is-map": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", @@ -13022,6 +13290,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -14267,6 +14547,16 @@ "devOptional": true, "license": "Apache-2.0" }, + "node_modules/longest-streak": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", + "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -14390,6 +14680,161 @@ "node": ">= 0.4" } }, + "node_modules/mdast-util-from-markdown": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-expression": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz", + "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-jsx": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz", + "integrity": "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-stringify-position": "^4.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdxjs-esm": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz", + "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-phrasing": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", + "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "integrity": "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-markdown": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz", + "integrity": "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "longest-streak": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/media-typer": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", @@ -14449,6 +14894,469 @@ "node": ">= 0.6" } }, + "node_modules/micromark": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.1.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.3" + } + }, + "node_modules/micromark-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-space": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-combine-extensions": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-string": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -15361,6 +16269,31 @@ "node": ">=6" } }, + "node_modules/parse-entities": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", + "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^2.0.0", + "character-entities-legacy": "^3.0.0", + "character-reference-invalid": "^2.0.0", + "decode-named-character-reference": "^1.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0", + "is-hexadecimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/parse-entities/node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", + "license": "MIT" + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -16150,6 +17083,16 @@ "integrity": "sha512-SVtmxhRE/CGkn3eZY1T6pC8Nln6Fr/lu1mKSgRud0eC73whjGfoAogbn78LkD8aFL0zz3bAFerKSnOl7NlErBA==", "license": "MIT" }, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/proxy-addr": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", @@ -16496,6 +17439,33 @@ "dev": true, "license": "MIT" }, + "node_modules/react-markdown": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", + "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "hast-util-to-jsx-runtime": "^2.0.0", + "html-url-attributes": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.0.0", + "unified": "^11.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "peerDependencies": { + "@types/react": ">=18", + "react": ">=18" + } + }, "node_modules/react-remove-scroll": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", @@ -16669,6 +17639,39 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/remark-parse": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", + "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-rehype": { + "version": "11.1.2", + "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz", + "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/remeda": { "version": "2.33.4", "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", @@ -17533,6 +18536,16 @@ "source-map": "^0.6.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -17841,6 +18854,20 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -17927,6 +18954,15 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/style-to-object": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.9" + } + }, "node_modules/styled-jsx": { "version": "5.1.6", "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", @@ -18542,6 +19578,26 @@ "tree-kill": "cli.js" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/trough": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", + "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -19027,6 +20083,93 @@ "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", "license": "MIT" }, + "node_modules/unified": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", + "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "bail": "^2.0.0", + "devlop": "^1.0.0", + "extend": "^3.0.0", + "is-plain-obj": "^4.0.0", + "trough": "^2.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -19220,6 +20363,34 @@ "node": ">= 0.8" } }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/watchpack": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.4.tgz", @@ -19650,9 +20821,19 @@ "zod": "^3.25.0 || ^4.0.0" } }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "packages/contracts": { "name": "@crosscode/contracts", - "version": "1.3.0", + "version": "1.4.0", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" @@ -19686,6 +20867,14 @@ "dev": true, "license": "MIT" }, + "packages/seo": { + "name": "@crosscode/seo", + "version": "1.0.0", + "license": "UNLICENSED", + "dependencies": { + "@crosscode/contracts": "*" + } + }, "packages/ui": { "name": "@crosscode/ui", "version": "0.0.0" diff --git a/packages/contracts/README.md b/packages/contracts/README.md index b7fbb65..1fac22f 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -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 diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 3b399c8..f2b0daa 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -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": { diff --git a/packages/contracts/samples/hub-heartbeat-response.json b/packages/contracts/samples/hub-heartbeat-response.json index e008138..f176478 100644 --- a/packages/contracts/samples/hub-heartbeat-response.json +++ b/packages/contracts/samples/hub-heartbeat-response.json @@ -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" } diff --git a/packages/contracts/samples/link-connect.json b/packages/contracts/samples/link-connect.json new file mode 100644 index 0000000..1883774 --- /dev/null +++ b/packages/contracts/samples/link-connect.json @@ -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" +} diff --git a/packages/contracts/samples/link-connected.json b/packages/contracts/samples/link-connected.json new file mode 100644 index 0000000..bf84fc0 --- /dev/null +++ b/packages/contracts/samples/link-connected.json @@ -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" +} diff --git a/packages/contracts/samples/link-disconnect.json b/packages/contracts/samples/link-disconnect.json new file mode 100644 index 0000000..c57127c --- /dev/null +++ b/packages/contracts/samples/link-disconnect.json @@ -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" +} diff --git a/packages/contracts/schemas/hub-heartbeat-request.json b/packages/contracts/schemas/hub-heartbeat-request.json index de10033..d801dcd 100644 --- a/packages/contracts/schemas/hub-heartbeat-request.json +++ b/packages/contracts/schemas/hub-heartbeat-request.json @@ -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" diff --git a/packages/contracts/schemas/hub-heartbeat-response.json b/packages/contracts/schemas/hub-heartbeat-response.json index c0b6aba..b699d0e 100644 --- a/packages/contracts/schemas/hub-heartbeat-response.json +++ b/packages/contracts/schemas/hub-heartbeat-response.json @@ -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": [ diff --git a/packages/contracts/schemas/link-connect.json b/packages/contracts/schemas/link-connect.json new file mode 100644 index 0000000..a0634ab --- /dev/null +++ b/packages/contracts/schemas/link-connect.json @@ -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" + ] +} diff --git a/packages/contracts/schemas/link-connected.json b/packages/contracts/schemas/link-connected.json new file mode 100644 index 0000000..7fde249 --- /dev/null +++ b/packages/contracts/schemas/link-connected.json @@ -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" + ] +} diff --git a/packages/contracts/schemas/link-disconnect.json b/packages/contracts/schemas/link-disconnect.json new file mode 100644 index 0000000..124dbcf --- /dev/null +++ b/packages/contracts/schemas/link-disconnect.json @@ -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" + ] +} diff --git a/packages/contracts/schemas/link-disconnected.json b/packages/contracts/schemas/link-disconnected.json new file mode 100644 index 0000000..a56a091 --- /dev/null +++ b/packages/contracts/schemas/link-disconnected.json @@ -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" + ] +} diff --git a/packages/contracts/schemas/link-error.json b/packages/contracts/schemas/link-error.json new file mode 100644 index 0000000..2618466 --- /dev/null +++ b/packages/contracts/schemas/link-error.json @@ -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" + ] +} diff --git a/packages/contracts/scripts/json-schemas.cjs b/packages/contracts/scripts/json-schemas.cjs index 671dc53..68789a3 100644 --- a/packages/contracts/scripts/json-schemas.cjs +++ b/packages/contracts/scripts/json-schemas.cjs @@ -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, }; } diff --git a/packages/contracts/src/event.ts b/packages/contracts/src/event.ts index 9c61391..8e73e7c 100644 --- a/packages/contracts/src/event.ts +++ b/packages/contracts/src/event.ts @@ -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; diff --git a/packages/contracts/src/hub.ts b/packages/contracts/src/hub.ts index 75fc751..6ee97d9 100644 --- a/packages/contracts/src/hub.ts +++ b/packages/contracts/src/hub.ts @@ -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; +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; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index edeeaef..d75dbc4 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -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"; diff --git a/packages/contracts/src/link.ts b/packages/contracts/src/link.ts new file mode 100644 index 0000000..4be64a0 --- /dev/null +++ b/packages/contracts/src/link.ts @@ -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; + +/** 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; + +/** 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; + +/** 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; + +export const linkDisconnectedSchema = z.object({ schema: z.literal(LINK_SCHEMA), type: z.literal("link.disconnected") }); +export type LinkDisconnected = z.infer; + +export const linkErrorSchema = z.object({ message: z.string(), code: z.enum(LINK_ERROR_CODES) }); +export type LinkError = z.infer; + +export type LinkMessage = LinkConnect | LinkConnected | LinkDisconnect; diff --git a/packages/contracts/src/signing.ts b/packages/contracts/src/signing.ts index e18e230..4036742 100644 --- a/packages/contracts/src/signing.ts +++ b/packages/contracts/src/signing.ts @@ -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>(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, 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" }; +} diff --git a/packages/contracts/tests/hub-signing.test.ts b/packages/contracts/tests/hub-signing.test.ts index 6668aa0..b3753da 100644 --- a/packages/contracts/tests/hub-signing.test.ts +++ b/packages/contracts/tests/hub-signing.test.ts @@ -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); + }); +}); diff --git a/packages/contracts/tests/json-schemas.test.ts b/packages/contracts/tests/json-schemas.test.ts index e951b27..984d614 100644 --- a/packages/contracts/tests/json-schemas.test.ts +++ b/packages/contracts/tests/json-schemas.test.ts @@ -36,6 +36,9 @@ const SAMPLE_SCHEMA: Record = { "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/)", () => { diff --git a/packages/contracts/tests/samples.test.ts b/packages/contracts/tests/samples.test.ts index 196930d..731b229 100644 --- a/packages/contracts/tests/samples.test.ts +++ b/packages/contracts/tests/samples.test.ts @@ -8,6 +8,9 @@ import { eventFeedSchema, eventSchema, hub, + linkConnectSchema, + linkConnectedSchema, + linkDisconnectSchema, identityClaimsSchema, userDeletedReplySchema, userExportReplySchema, @@ -36,6 +39,9 @@ const SCHEMAS: Record = { "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", () => { diff --git a/packages/seo/README.md b/packages/seo/README.md new file mode 100644 index 0000000..d0e8021 --- /dev/null +++ b/packages/seo/README.md @@ -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 `` | + +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). diff --git a/packages/seo/jest.config.js b/packages/seo/jest.config.js new file mode 100644 index 0000000..8b0f9cf --- /dev/null +++ b/packages/seo/jest.config.js @@ -0,0 +1,7 @@ +module.exports = { + testEnvironment: "node", + testMatch: ["/tests/**/*.test.ts"], + transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] }, + moduleFileExtensions: ["ts", "js", "json"], + modulePathIgnorePatterns: ["/dist/"], +}; diff --git a/packages/seo/package.json b/packages/seo/package.json new file mode 100644 index 0000000..77bb480 --- /dev/null +++ b/packages/seo/package.json @@ -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": "*" + } +} diff --git a/packages/seo/src/church.ts b/packages/seo/src/church.ts new file mode 100644 index 0000000..c615679 --- /dev/null +++ b/packages/seo/src/church.ts @@ -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; + +const DAYS: Record = { + 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 } : {}), + }; + }), + } + : {}), + }; +} diff --git a/packages/seo/src/event.ts b/packages/seo/src/event.ts new file mode 100644 index 0000000..f1276be --- /dev/null +++ b/packages/seo/src/event.ts @@ -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; + +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 } : {}), + })), + } + : {}), + }; +} diff --git a/packages/seo/src/index.ts b/packages/seo/src/index.ts new file mode 100644 index 0000000..a01329e --- /dev/null +++ b/packages/seo/src/index.ts @@ -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"; diff --git a/packages/seo/src/meta.ts b/packages/seo/src/meta.ts new file mode 100644 index 0000000..3aa458f --- /dev/null +++ b/packages/seo/src/meta.ts @@ -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 `` in the text. */ +export function jsonLdString(data: unknown): string { + return JSON.stringify(data).replace(/(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).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: "" })).not.toContain(""); + }); +}); diff --git a/packages/seo/tsconfig.json b/packages/seo/tsconfig.json new file mode 100644 index 0000000..7f5ccf8 --- /dev/null +++ b/packages/seo/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": ".", + "types": ["node", "jest"] + }, + "include": ["src", "tests", "tsup.config.ts"] +} diff --git a/packages/seo/tsup.config.ts b/packages/seo/tsup.config.ts new file mode 100644 index 0000000..4ac09e6 --- /dev/null +++ b/packages/seo/tsup.config.ts @@ -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" }), +}); diff --git a/scripts/products/events.sh b/scripts/products/events.sh index 9c7c144..c6b3f01 100644 --- a/scripts/products/events.sh +++ b/scripts/products/events.sh @@ -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 } diff --git a/scripts/tests/events.bats b/scripts/tests/events.bats new file mode 100644 index 0000000..48a8674 --- /dev/null +++ b/scripts/tests/events.bats @@ -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" ] +}