From 8a930d07c601334d464e59025836dafbc1da6afb Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 18 Nov 2026 12:24:29 +0200 Subject: [PATCH] Events 2.4.0 backend: protocol v2, Linked products, the event feed - Hub client: register and heartbeat on protocol v2 with the site's Ed25519 key (sent on the heartbeat until the Hub has it); falls back to v1 for a day if the Hub refuses v2, so the licence always refreshes. - crosscode.link/1 Connect / Disconnect, both directions, trusted through the Hub's cached linkedProducts (ProductLink, LinkNonce). - GET /api/feed/v1/events from FeedEntry (go-live, closing and selling out are changes; deactivated events go in deleted), event.changed to connected products, and showing their events (ImportedEvent). - /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains crosscodeEvent and priceRangeCents for the JSON-LD. - Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing. Co-Authored-By: Claude Opus 5.5 --- apps/events/SETTINGS.md | 4 +- apps/events/backend/.env.example | 4 +- apps/events/backend/package.json | 1 + .../migration.sql | 54 + apps/events/backend/prisma/schema.prisma | 65 + apps/events/backend/src/app.js | 3 + apps/events/backend/src/config/db.js | 27 +- apps/events/backend/src/feed/build.ts | 244 +++ apps/events/backend/src/feed/context.ts | 44 + apps/events/backend/src/feed/entries.ts | 139 ++ apps/events/backend/src/feed/notify.ts | 56 + apps/events/backend/src/feed/sync.ts | 74 + apps/events/backend/src/hub/client.js | 137 +- apps/events/backend/src/jobs/index.js | 10 + apps/events/backend/src/links/connect.ts | 186 ++ apps/events/backend/src/links/http.ts | 75 + apps/events/backend/src/links/routes.ts | 100 + apps/events/backend/src/links/store.ts | 89 + apps/events/backend/src/v2/index.ts | 1 + .../backend/src/v2/resources/eventDetails.ts | 9 +- .../src/v2/resources/linkedProducts.ts | 277 +++ .../backend/tests/hubConnectFromEnv.test.js | 1 + .../backend/tests/linkedProducts.test.js | 486 +++++ .../backend/tests/support/fakeFeedDb.js | 115 ++ apps/events/frontend/package.json | 3 + .../frontend/src/lib/api-v2/openapi.json | 1664 ++++++++++++++++- .../frontend/src/lib/api-v2/schema.d.ts | 825 ++++++++ package-lock.json | 1184 +++++++++++- packages/contracts/package.json | 7 + packages/contracts/src/event.ts | 7 + 30 files changed, 5874 insertions(+), 17 deletions(-) create mode 100644 apps/events/backend/prisma/migrations/20261120120000_linked_products/migration.sql create mode 100644 apps/events/backend/src/feed/build.ts create mode 100644 apps/events/backend/src/feed/context.ts create mode 100644 apps/events/backend/src/feed/entries.ts create mode 100644 apps/events/backend/src/feed/notify.ts create mode 100644 apps/events/backend/src/feed/sync.ts create mode 100644 apps/events/backend/src/links/connect.ts create mode 100644 apps/events/backend/src/links/http.ts create mode 100644 apps/events/backend/src/links/routes.ts create mode 100644 apps/events/backend/src/links/store.ts create mode 100644 apps/events/backend/src/v2/resources/linkedProducts.ts create mode 100644 apps/events/backend/tests/linkedProducts.test.js create mode 100644 apps/events/backend/tests/support/fakeFeedDb.js 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/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..9ee8afa 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", 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/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..584cc8c --- /dev/null +++ b/apps/events/backend/tests/linkedProducts.test.js @@ -0,0 +1,486 @@ +// 2.4.0 (docs/EVENTS-2.4-PLAN.md §8): the event feed, Linked products / Connect, showing events +// from linked products, and the v2 heartbeat. In-memory database (tests/support/fakeFeedDb.js). +jest.mock('../src/config/db', () => require('./support/fakeFeedDb')); +jest.mock('../src/utils/settingsCache', () => { + const db = require('./support/fakeFeedDb'); + return { + getSetting: async (key, fallback = '') => (db.t.appSetting.get(key)?.value ?? fallback), + getSettingSync: () => '', + invalidate: () => {}, + warmCache: async () => {}, + ENCRYPTED_KEYS: new Set(), + }; +}); +const mockSold = new Map(); +jest.mock('../src/utils/stock', () => ({ takenCount: async ({ eventOptionId, sessionId }) => mockSold.get(sessionId ? `${eventOptionId}:${sessionId}` : eventOptionId) || 0 })); +const mockTasks = []; +jest.mock('../src/jobs', () => ({ enqueueTask: async (name, data) => { mockTasks.push([name, data]); return { queued: true }; } })); + +process.env.WEBHOOKS_ALLOW_PRIVATE = 'true'; +process.env.FRONTEND_URL = 'https://events.hope.test'; +process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption'; + +const express = require('express'); +const request = require('supertest'); +const { eventSchema, eventFeedSchema, linkConnectSchema, hub: hubContract } = require('@crosscode/contracts'); +const signing = require('@crosscode/contracts/signing'); +const db = require('./support/fakeFeedDb'); +const path = require('path'); +const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples'); +const contractSample = (name) => JSON.parse(require('fs').readFileSync(path.join(SAMPLES, name), 'utf8')); +const { encrypt } = require('../src/utils/encryption'); +const { buildCrosscodeEvent, plainToMarkdown, absolute } = require('../src/feed/build'); +const { refreshFeed, feedResponse } = require('../src/feed/entries'); +const { syncLink } = require('../src/feed/sync'); +const connect = require('../src/links/connect'); +const store = require('../src/links/store'); +const { crossProductRouter } = require('../src/links/routes'); + +const EVENTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c'; +const WEBSITE_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02'; +const WEBSITE_URL = 'https://www.hope.test'; +const NOW = new Date('2026-11-20T10:00:00.000Z'); +const DAY = 24 * 3600e3; + +const ctx = (over = {}) => ({ installId: EVENTS_ID, baseUrl: 'https://events.hope.test', timezone: 'Africa/Johannesburg', campusesOn: false, now: NOW, ...over }); + +let n = 0; +const uuid = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`; + +function eventRow(over = {}) { + const id = over.id || uuid(); + return { + id, + title: 'Youth Camp', + description: 'Three days away.\nBring a *sleeping bag*.', + startDate: new Date(NOW.getTime() + 30 * DAY), + endDate: new Date(NOW.getTime() + 32 * DAY), + goLiveAt: new Date(NOW.getTime() - DAY), + registrationDeadline: null, + picture: '/uploads/camp.jpg', + location: 'Camp Wartburg', + requiresRegistration: true, + waitlistEnabled: false, + scheduleType: 'single', + attendanceMode: 'whole', + lateJoinEnabled: false, + lateJoinUntilSessionId: null, + kidsOptionId: null, + volunteerOptionId: null, + isActive: true, + isHidden: false, + campus: null, + series: null, + sessions: [], + eventOptions: [ + { id: `${id}-adult`, price: 450, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] }, + { id: `${id}-child`, price: 300, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] }, + { id: `${id}-tshirt`, price: 120, isMainTicket: false, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] }, + ], + ...over, + }; +} + +const keys = { events: signing.generateEd25519(), website: signing.generateEd25519() }; +const pem = (k) => signing.ed25519PublicToPem(k.publicKey); + +async function setUpSite({ linked = true } = {}) { + db.reset(); + store.forgetKeyPair(); + db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID }); + db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) }); + db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) }); + if (linked) await store.saveLinkedProducts([{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }]); +} + +beforeEach(async () => { + mockSold.clear(); + mockTasks.length = 0; + await setUpSite(); + delete global.fetch; +}); + +// ─── Building crosscode.event/1 ─────────────────────────────────────────────── + +describe('crosscode.event/1 from an event', () => { + test('a ticketed event passes the contract, with the lowest main ticket as the price', () => { + const { event, priceRangeCents } = buildCrosscodeEvent(eventRow(), new Map(), ctx()); + expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]); + expect(event.origin).toEqual({ product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${event.id}` }); + expect(event.registration).toMatchObject({ mode: 'origin', status: 'open', priceFrom: { amountCents: 30000, currency: 'ZAR' } }); + expect(priceRangeCents).toEqual({ lowCents: 30000, highCents: 45000 }); + expect(event.imageUrl).toBe('https://events.hope.test/api/uploads/camp.jpg'); + expect(event.location).toEqual({ name: 'Camp Wartburg', address: null, onlineUrl: null }); + }); + + test('never carries the contact person, kids or volunteer tickets', () => { + const row = eventRow({ contactName: 'Jane', contactPhone: '082', contactEmail: 'jane@x.co.za' }); + row.kidsOptionId = row.eventOptions[1].id; + row.eventOptions[1].price = 0; + const json = JSON.stringify(buildCrosscodeEvent(row, new Map(), ctx()).event); + expect(json).not.toMatch(/Jane|082|jane@/); + expect(buildCrosscodeEvent(row, new Map(), ctx()).event.registration.priceFrom).toEqual({ amountCents: 45000, currency: 'ZAR' }); + }); + + test.each([ + ['not_open', { goLiveAt: new Date(NOW.getTime() + DAY) }, new Map()], + ['closed', { registrationDeadline: new Date(NOW.getTime() - 3600e3) }, new Map()], + ])('registration %s', (status, over, avail) => { + expect(buildCrosscodeEvent(eventRow(over), avail, ctx()).event.registration.status).toBe(status); + }); + + test('full when every main ticket is limited and sold out; waitlist when it has one', () => { + const row = eventRow(); + row.eventOptions[0].stockLimit = 10; + row.eventOptions[1].stockLimit = 5; + const soldOut = new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 0]]); + expect(buildCrosscodeEvent(row, soldOut, ctx()).event.registration.status).toBe('full'); + expect(buildCrosscodeEvent({ ...row, waitlistEnabled: true }, soldOut, ctx()).event.registration.status).toBe('waitlist'); + // One main ticket still has places: open. + expect(buildCrosscodeEvent(row, new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 2]]), ctx()).event.registration.status).toBe('open'); + }); + + test('contact-only and free events', () => { + expect(buildCrosscodeEvent(eventRow({ requiresRegistration: false }), new Map(), ctx()).event.registration).toEqual({ mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null }); + const free = eventRow(); + for (const o of free.eventOptions) o.price = 0; + const built = buildCrosscodeEvent(free, new Map(), ctx()); + expect(built.event.registration.priceFrom).toBeNull(); + expect(built.priceRangeCents).toBeNull(); + }); + + test('a multi-day event: sessions, and start/end from the sessions that still run', () => { + const s = (d, cancelled = false) => ({ id: uuid(), label: `Week ${d}`, startsAt: new Date(NOW.getTime() + d * 7 * DAY), endsAt: new Date(NOW.getTime() + d * 7 * DAY + 2 * 3600e3), location: null, cancelledAt: cancelled ? NOW : null }); + const sessions = [s(1), s(2), s(3, true)]; + const { event } = buildCrosscodeEvent(eventRow({ scheduleType: 'sessions', sessions }), new Map(), ctx()); + expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]); + expect(event.sessions).toHaveLength(3); + expect(event.endsAt).toBe(sessions[1].endsAt.toISOString()); + }); + + test('an online event, and the campus only while campuses are on', () => { + const row = eventRow({ location: 'https://youtube.com/live/abc', campus: { slug: 'meyerton', name: 'Meyerton' } }); + expect(buildCrosscodeEvent(row, new Map(), ctx()).event).toMatchObject({ location: { onlineUrl: 'https://youtube.com/live/abc' }, campus: null }); + expect(buildCrosscodeEvent(row, new Map(), ctx({ campusesOn: true })).event.campus).toEqual({ slug: 'meyerton', name: 'Meyerton' }); + }); + + test('plain text descriptions read the same as markdown', () => { + expect(plainToMarkdown('Bring a *sleeping bag*\n- not a list\n1. not numbered\n\n# not a heading')).toBe('Bring a \\*sleeping bag\\* \n\\- not a list \n1\\. not numbered\n\n\\# not a heading'); + expect(plainToMarkdown(' ')).toBeNull(); + expect(absolute('https://e.test', 'https://cdn.test/x.jpg')).toBe('https://cdn.test/x.jpg'); + }); +}); + +// ─── The published feed ─────────────────────────────────────────────────────── + +describe('the feed', () => { + const put = (row) => db.t.event.set(row.id, row); + + test('publishes public events, and updatedSince returns exactly what changed', async () => { + const a = eventRow(); + const hidden = eventRow({ isHidden: true }); + const later = eventRow({ goLiveAt: new Date(NOW.getTime() + 2 * 3600e3) }); + [a, hidden, later].forEach(put); + + const first = await refreshFeed(NOW); + expect(first.changed).toEqual([a.id]); + const full = await feedResponse(null, NOW); + expect(eventFeedSchema.safeParse(full).success).toBe(true); + expect(full.events.map((e) => e.id)).toEqual([a.id]); + + // Nothing changed: nothing new since. + const t1 = new Date(NOW.getTime() + 60e3); + expect((await refreshFeed(t1)).changed).toEqual([]); + expect((await feedResponse(NOW, t1)).events).toEqual([]); + + // Going live changes no Event row, but shows up. + const t2 = new Date(NOW.getTime() + 3 * 3600e3); + expect((await refreshFeed(t2)).changed).toEqual([later.id]); + expect((await feedResponse(t1, t2)).events.map((e) => e.id)).toEqual([later.id]); + }); + + test('selling out is a change; deactivating puts the event in deleted', async () => { + const a = eventRow(); + a.eventOptions[0].stockLimit = 2; + a.eventOptions[1].stockLimit = 2; + put(a); + await refreshFeed(NOW); + + mockSold.set(a.eventOptions[0].id, 2); + mockSold.set(a.eventOptions[1].id, 2); + const t1 = new Date(NOW.getTime() + 60e3); + expect((await refreshFeed(t1)).changed).toEqual([a.id]); + const after = await feedResponse(NOW, t1); + expect(after.events[0].registration.status).toBe('full'); + expect(after.events[0].updatedAt).toBe(t1.toISOString()); + + put({ ...a, isActive: false }); + const t2 = new Date(NOW.getTime() + 120e3); + expect((await refreshFeed(t2)).removed).toEqual([a.id]); + const gone = await feedResponse(t1, t2); + expect(gone.events).toEqual([]); + expect(gone.deleted).toEqual([{ id: a.id, deletedAt: t2.toISOString() }]); + // A full fetch no longer lists it. + expect((await feedResponse(null, t2)).events).toEqual([]); + }); + + test('an event that ended a month ago drops out quietly (not deleted)', async () => { + const a = eventRow({ startDate: new Date(NOW.getTime() - 2 * DAY), endDate: new Date(NOW.getTime() - DAY) }); + put(a); + await refreshFeed(NOW); + const later = new Date(NOW.getTime() + 31 * DAY); + const r = await refreshFeed(later); + expect(r.removed).toEqual([]); + expect((await feedResponse(NOW, later)).deleted).toEqual([]); + expect(db.t.feedEntry.has(a.id)).toBe(false); + }); + + test('without a Hub install id there is no feed', async () => { + db.t.appSetting.delete('hub_install_id'); + put(eventRow()); + expect(await refreshFeed(NOW)).toEqual({ changed: [], removed: [], skipped: [] }); + }); +}); + +// ─── Connect ────────────────────────────────────────────────────────────────── + +function connectMessage(over = {}, key = keys.website) { + return signing.signLink({ + schema: 'crosscode.link/1', + type: 'link.connect', + from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, + to: { installId: EVENTS_ID }, + secret: signing.newLinkSecret(), + issuedAt: new Date().toISOString(), + nonce: signing.newLinkNonce(), + ...over, + }, key.privateKeyPem); +} + +describe('Connect from a linked product', () => { + test('a listed product connects; the reply is signed with this site\'s key and echoes the nonce', async () => { + const m = connectMessage(); + const reply = await connect.acceptConnect(m, '1.2.3.4'); + expect(signing.verifyLink(reply, pem(keys.events))).toEqual({ ok: true }); + expect(reply).toMatchObject({ type: 'link.connected', inReplyTo: m.nonce, to: { installId: WEBSITE_ID }, from: { product: 'events', installId: EVENTS_ID } }); + const link = db.t.productLink.get(WEBSITE_ID); + expect(link).toMatchObject({ product: 'website', url: WEBSITE_URL, connectedById: null }); + expect(db.t.audit.map((a) => a.action)).toEqual(['product_link_connected']); + }); + + test.each([ + ['not listed by the Hub', async () => { await store.saveLinkedProducts([]); return connectMessage(); }, 'NOT_LINKED'], + ['signed with another key', async () => connectMessage({}, signing.generateEd25519()), 'BAD_SIGNATURE'], + ['too old', async () => connectMessage({ issuedAt: new Date(Date.now() - 10 * 60e3).toISOString() }), 'STALE_REQUEST'], + ['for another install', async () => connectMessage({ to: { installId: WEBSITE_ID } }), 'WRONG_INSTALL'], + ['claiming another product', async () => connectMessage({ from: { product: 'app', installId: WEBSITE_ID, url: WEBSITE_URL } }), 'NOT_LINKED'], + ['not a link message', async () => ({ hello: 'world' }), 'INVALID_REQUEST'], + ])('refused when %s', async (_name, make, code) => { + await expect(connect.acceptConnect(await make(), null)).rejects.toMatchObject({ code }); + expect(db.t.productLink.size).toBe(0); + }); + + test('a replayed message is refused', async () => { + const m = connectMessage(); + await connect.acceptConnect(m, null); + await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' }); + }); + + test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => { + await connect.acceptConnect(connectMessage(), null); + db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID }); + const msg = (key) => signing.signLink({ schema: 'crosscode.link/1', type: 'link.disconnect', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce() }, key.privateKeyPem); + await expect(connect.acceptDisconnect(msg(signing.generateEd25519()), null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' }); + await connect.acceptDisconnect(msg(keys.website), null); + expect(db.t.productLink.size).toBe(0); + expect(db.t.importedEvent.size).toBe(0); + }); +}); + +describe('Connect from this site', () => { + const admin = { id: 'admin-1', role: 'admin' }; + + function siblingAnswers(make) { + global.fetch = jest.fn(async (url, init) => { + const body = JSON.parse(init.body); + expect(String(url)).toBe(`${WEBSITE_URL}/api/links/v1/connect`); + expect(linkConnectSchema.safeParse(body).success).toBe(true); + expect(signing.verifyLink(body, pem(keys.events))).toEqual({ ok: true }); + const reply = make(body); + return new Response(JSON.stringify(reply.body), { status: reply.status || 200, headers: { 'content-type': 'application/json' } }); + }); + } + const goodReply = (body, key = keys.website, over = {}) => ({ + body: signing.signLink({ schema: 'crosscode.link/1', type: 'link.connected', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, inReplyTo: body.nonce, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce(), ...over }, key.privateKeyPem), + }); + + test('connects when the sibling answers, signed with its listed key', async () => { + let sentSecret; + siblingAnswers((body) => { sentSecret = body.secret; return goodReply(body); }); + await connect.connectTo(WEBSITE_ID, admin, null); + const link = db.t.productLink.get(WEBSITE_ID); + expect(link.connectedById).toBe('admin-1'); + expect(require('../src/utils/encryption').decrypt(link.secret)).toBe(sentSecret); + }); + + test.each([ + ['signed with another key', (body) => goodReply(body, signing.generateEd25519())], + ['for another message', (body) => goodReply(body, keys.website, { inReplyTo: signing.newLinkNonce() })], + ])('refuses an answer %s', async (_name, make) => { + siblingAnswers(make); + await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' }); + expect(db.t.productLink.size).toBe(0); + }); + + test('passes on the sibling\'s refusal', async () => { + siblingAnswers(() => ({ status: 403, body: { message: 'Not linked yet', code: 'NOT_LINKED' } })); + await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' }); + }); + + test('only to a product the Hub listed', async () => { + await expect(connect.connectTo('3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09', admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' }); + }); +}); + +// ─── Showing events from a linked product ────────────────────────────────────── + +describe('events from a linked product', () => { + const sample = () => contractSample('event-simple.json'); + const linkRow = () => ({ installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('s'), connectedAt: NOW, connectedById: null, showEvents: true, lastSyncAt: null, lastGoodAt: null, lastSyncError: null }); + const feedOf = (events, deleted = []) => ({ schema: 'crosscode.event-feed/1', generatedAt: NOW.toISOString(), events, deleted }); + const answer = (body, status = 200) => { global.fetch = jest.fn(async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); }; + + test('imports its events, skips a bad one and one that claims another origin', async () => { + db.t.productLink.set(WEBSITE_ID, linkRow()); + const good = sample(); + const bad = { ...sample(), id: 'not-a-uuid' }; + const spoofed = { ...sample(), id: uuid(), origin: { ...sample().origin, installId: EVENTS_ID } }; + answer(feedOf([good, bad, spoofed])); + const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW); + expect(r).toMatchObject({ ok: true, imported: 1, rejected: 1, skipped: 1 }); + expect([...db.t.importedEvent.keys()]).toEqual([`website:${good.id}`]); + expect(String(global.fetch.mock.calls[0][0])).toBe(`${WEBSITE_URL}/api/feed/v1/events`); + expect(db.t.productLink.get(WEBSITE_ID).lastGoodAt.toISOString()).toBe(NOW.toISOString()); + }); + + test('a source that is down keeps its last events and shows the error', async () => { + db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW }); + db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID }); + global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); }); + const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW); + expect(r.ok).toBe(false); + expect(db.t.importedEvent.size).toBe(1); + expect(db.t.productLink.get(WEBSITE_ID).lastSyncError).toMatch(/could not be reached/); + // It fetched what changed since a little before the last good fetch. + expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince='); + }); + + test('deleted events go; never re-published in this site\'s own feed', async () => { + db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW }); + const e = sample(); + answer(feedOf([e])); + await syncLink(db.t.productLink.get(WEBSITE_ID), NOW); + answer(feedOf([], [{ id: e.id, deletedAt: NOW.toISOString() }])); + await syncLink(db.t.productLink.get(WEBSITE_ID), NOW); + expect(db.t.importedEvent.size).toBe(0); + // The feed is built from this site's own events only. + db.t.importedEvent.set('website:y', { key: 'website:y', linkId: WEBSITE_ID, payload: e }); + await refreshFeed(NOW); + expect((await feedResponse(null, NOW)).events).toEqual([]); + }); +}); + +// ─── The endpoints other products call ───────────────────────────────────────── + +describe('/api/feed/v1 and /api/links/v1', () => { + const app = () => express().use('/api', crossProductRouter()); + + test('the feed: on by default, 404 when publishing is off, 400 for a bad updatedSince', async () => { + // The route works on the real clock. + const now = Date.now(); + db.t.event.set('e', eventRow({ id: uuid(), goLiveAt: new Date(now - DAY), startDate: new Date(now + 10 * DAY), endDate: new Date(now + 11 * DAY) })); + await refreshFeed(new Date()); + const res = await request(app()).get('/api/feed/v1/events'); + expect(res.status).toBe(200); + expect(eventFeedSchema.safeParse(res.body).success).toBe(true); + expect(res.body.events).toHaveLength(1); + expect((await request(app()).get('/api/feed/v1/events?updatedSince=yesterday')).body.code).toBe('INVALID_REQUEST'); + db.t.appSetting.set('feed_publish', { key: 'feed_publish', value: 'false' }); + expect((await request(app()).get('/api/feed/v1/events')).status).toBe(404); + }); + + test('event.changed: checked with the link\'s secret, then a fetch is queued', async () => { + db.t.productLink.set(WEBSITE_ID, { installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('link-secret'), connectedAt: NOW, showEvents: true }); + const body = JSON.stringify({ schema: 'crosscode.event-feed/1', type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [uuid()] }); + const send = (secret, sender = WEBSITE_ID) => request(app()).post('/api/feed/v1/changed').set('Content-Type', 'application/json') + .set(signing.signedHeaders(signing.LINK_HEADERS, { senderId: sender, secret, rawBody: body })).send(body); + expect((await send('wrong')).status).toBe(401); + expect((await send('link-secret', '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09')).status).toBe(404); + const ok = await send('link-secret'); + expect(ok.status).toBe(202); + expect(mockTasks).toEqual([['feed-sync-link', { installId: WEBSITE_ID }]]); + }); + + test('connect over HTTP, and errors as { message, code }', async () => { + const res = await request(app()).post('/api/links/v1/connect').send(connectMessage()); + expect(res.status).toBe(200); + expect(res.body.type).toBe('link.connected'); + const bad = await request(app()).post('/api/links/v1/connect').send(connectMessage({}, signing.generateEd25519())); + expect(bad.status).toBe(401); + expect(bad.body).toEqual({ message: expect.any(String), code: 'BAD_SIGNATURE' }); + const notJson = await request(app()).post('/api/links/v1/connect').set('Content-Type', 'application/json').send('{oops'); + expect(notJson.body.code).toBe('INVALID_REQUEST'); + }); +}); + +// ─── The v2 heartbeat ───────────────────────────────────────────────────────── + +describe('protocol v2 heartbeat', () => { + const report = require('../src/hub/report'); + const sampleHb = contractSample('hub-heartbeat-events.json'); + + beforeEach(() => { + jest.spyOn(report, 'health').mockResolvedValue({ ...sampleHb.health, jobs: null, pendingMigrations: null }); + jest.spyOn(report, 'stats').mockResolvedValue(sampleHb.stats); + }); + afterEach(() => jest.restoreAllMocks()); + + test('fits the contract (gaps in health filled), with the public key until the Hub has it', async () => { + const client = require('../src/hub/client'); + const { body, v2 } = await client.heartbeatBody(); + expect(v2).toBe(true); + expect(hubContract.heartbeatRequestSchema.safeParse(body).error?.issues ?? []).toEqual([]); + expect(body.publicKey).toBe(pem(keys.events)); + await store.setPublicKeyStatus('saved'); + expect((await client.heartbeatBody()).body).not.toHaveProperty('publicKey'); + await store.setPublicKeyStatus('mismatch'); + expect((await client.heartbeatBody()).body.publicKey).toBe(pem(keys.events)); + }); + + test('a Hub that refuses v2 gets the same heartbeat as v1, and v1 for a day', async () => { + const client = require('../src/hub/client'); + db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') }); + const sent = []; + global.fetch = jest.fn(async (_url, init) => { + const b = JSON.parse(init.body); + sent.push(b.protocolVersion); + if (b.protocolVersion === 2) return new Response(JSON.stringify({ message: 'Protocol 2 is not supported', code: 'UNSUPPORTED_PROTOCOL' }), { status: 400 }); + return new Response(JSON.stringify({ licence: 'x', latestVersion: null }), { status: 200 }); + }); + const r = await client.heartbeat(); + expect(r).toMatchObject({ ok: true, protocol: 1 }); + expect(sent).toEqual([2, 1]); + await client.heartbeat(); + expect(sent).toEqual([2, 1, 1]); + }); + + test('saves the church\'s other products from the reply', async () => { + const client = require('../src/hub/client'); + db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') }); + const listed = [{ product: 'app', installId: '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04', url: 'https://app.hope.test', publicKey: pem(keys.website) }, { product: 'bogus' }]; + global.fetch = jest.fn(async () => new Response(JSON.stringify({ licence: 'x', latestVersion: null, linkedProducts: listed, publicKeyStatus: 'saved' }), { status: 200 })); + await client.heartbeat(); + expect((await store.linkedProducts()).map((l) => l.product)).toEqual(['app']); + expect(await store.publicKeyStatus()).toBe('saved'); + }); +}); 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/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/lib/api-v2/openapi.json b/apps/events/frontend/src/lib/api-v2/openapi.json index 9743f11..ffb611a 100644 --- a/apps/events/frontend/src/lib/api-v2/openapi.json +++ b/apps/events/frontend/src/lib/api-v2/openapi.json @@ -103,6 +103,9 @@ }, { "name": "AI" + }, + { + "name": "Linked products" } ], "paths": { @@ -2435,6 +2438,61 @@ ], "additionalProperties": {} } + }, + "crosscodeEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event/1" + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + "required": [ + "schema", + "id" + ], + "additionalProperties": {} + }, + { + "type": "null" + } + ], + "description": "The event as crosscode.event/1 (2.4.0), what its page builds its schema.org JSON-LD from (@crosscode/seo). The same shape the event feed publishes." + }, + "priceRangeCents": { + "anyOf": [ + { + "type": "object", + "properties": { + "lowCents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "highCents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "lowCents", + "highCents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "The lowest and highest current ticket prices in cents, for the JSON-LD price range (null when free)" } }, "required": [ @@ -2453,7 +2511,9 @@ "seriesId", "picture", "form", - "attachments" + "attachments", + "crosscodeEvent", + "priceRangeCents" ], "additionalProperties": {} } @@ -70578,6 +70638,1608 @@ } } } + }, + "/linked-products": { + "get": { + "tags": [ + "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.\n\n**Who:** Admins only.", + "operationId": "getLinked-products", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-products/settings": { + "put": { + "tags": [ + "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).\n\n**Who:** Admins only.", + "operationId": "putLinked-productsSettings", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "publishEvents": { + "type": "boolean" + } + }, + "required": [ + "publishEvents" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-products/{installId}/connect": { + "post": { + "tags": [ + "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.\n\n**Who:** Admins only.", + "operationId": "postLinked-productsInstallIdConnect", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "installId", + "in": "path", + "required": true, + "description": "The product's Hub install id", + "schema": { + "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)$" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-products/{installId}/disconnect": { + "post": { + "tags": [ + "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.\n\n**Who:** Admins only.", + "operationId": "postLinked-productsInstallIdDisconnect", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "installId", + "in": "path", + "required": true, + "description": "The product's Hub install id", + "schema": { + "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)$" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + }, + "otherSideTold": { + "type": "boolean" + }, + "problem": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products", + "otherSideTold", + "problem" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-products/{installId}": { + "put": { + "tags": [ + "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.\n\n**Who:** Admins only.", + "operationId": "putLinked-productsInstallId", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "installId", + "in": "path", + "required": true, + "description": "The product's Hub install id", + "schema": { + "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)$" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "showEvents": { + "type": "boolean" + } + }, + "required": [ + "showEvents" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-products/{installId}/sync": { + "post": { + "tags": [ + "Linked products" + ], + "summary": "Fetch a product's events now", + "description": "**Who:** Admins only.", + "operationId": "postLinked-productsInstallIdSync", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "installId", + "in": "path", + "required": true, + "description": "The product's Hub install id", + "schema": { + "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)$" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "hubConnected": { + "type": "boolean" + }, + "keyKnownToHub": { + "type": "boolean", + "description": "The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it" + }, + "keyMismatch": { + "type": "boolean", + "description": "The Hub has a different key for this site (ask the provider to clear it)" + }, + "publishEvents": { + "type": "boolean" + }, + "products": { + "type": "array", + "items": { + "type": "object", + "properties": { + "installId": { + "type": "string" + }, + "product": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "listed": { + "type": "boolean", + "description": "In the list the Hub last gave (false: connected before, no longer listed)" + }, + "publishesEvents": { + "type": "boolean" + }, + "link": { + "anyOf": [ + { + "type": "object", + "properties": { + "connectedAt": { + "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))$" + }, + "connectedBy": { + "description": "Who pressed Connect here; null when the other product connected", + "type": [ + "string", + "null" + ] + }, + "showEvents": { + "type": "boolean" + }, + "lastSyncAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ] + }, + "lastGoodAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When its events were last fetched successfully" + }, + "lastSyncError": { + "type": [ + "string", + "null" + ] + }, + "importedEvents": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "connectedAt", + "connectedBy", + "showEvents", + "lastSyncAt", + "lastGoodAt", + "lastSyncError", + "importedEvents" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "null = not connected" + } + }, + "required": [ + "installId", + "product", + "name", + "url", + "listed", + "publishesEvents", + "link" + ], + "additionalProperties": false + } + } + }, + "required": [ + "hubConnected", + "keyKnownToHub", + "keyMismatch", + "publishEvents", + "products" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-events": { + "get": { + "tags": [ + "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.\n\n**Who:** Anyone.", + "operationId": "getLinked-events", + "parameters": [ + { + "name": "campus", + "in": "query", + "required": false, + "description": "A campus slug (its events, church-wide ones and ones for a campus this site doesn't have), or 'all' for church-wide only", + "schema": { + "type": "string", + "maxLength": 64 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "How many per page", + "schema": { + "default": 50, + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "\":\", unique across products" + }, + "product": { + "type": "string" + }, + "productName": { + "type": "string" + }, + "event": { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event/1" + }, + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "startsAt": { + "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))$" + }, + "endsAt": { + "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))$" + } + }, + "required": [ + "schema", + "id", + "title", + "startsAt", + "endsAt" + ], + "additionalProperties": {}, + "description": "The event as crosscode.event/1, as the other product published it" + } + }, + "required": [ + "key", + "product", + "productName", + "event" + ], + "additionalProperties": false + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/linked-events/{product}/{id}": { + "get": { + "tags": [ + "Events" + ], + "summary": "One event from another of the church's products", + "description": "**Who:** Anyone.", + "operationId": "getLinked-eventsProductId", + "parameters": [ + { + "name": "product", + "in": "path", + "required": true, + "description": "The product the event comes from", + "schema": { + "type": "string", + "enum": [ + "website", + "app" + ] + } + }, + { + "name": "id", + "in": "path", + "required": true, + "description": "The event's id in that product", + "schema": { + "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)$" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "\":\", unique across products" + }, + "product": { + "type": "string" + }, + "productName": { + "type": "string" + }, + "event": { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event/1" + }, + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "startsAt": { + "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))$" + }, + "endsAt": { + "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))$" + } + }, + "required": [ + "schema", + "id", + "title", + "startsAt", + "endsAt" + ], + "additionalProperties": {}, + "description": "The event as crosscode.event/1, as the other product published it" + }, + "lastSyncedAt": { + "anyOf": [ + { + "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))$" + }, + { + "type": "null" + } + ], + "description": "When the copy was last refreshed from its product" + } + }, + "required": [ + "key", + "product", + "productName", + "event", + "lastSyncedAt" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } }, "components": { diff --git a/apps/events/frontend/src/lib/api-v2/schema.d.ts b/apps/events/frontend/src/lib/api-v2/schema.d.ts index fb03a23..680848b 100644 --- a/apps/events/frontend/src/lib/api-v2/schema.d.ts +++ b/apps/events/frontend/src/lib/api-v2/schema.d.ts @@ -7326,6 +7326,178 @@ export interface paths { patch?: never; trace?: never; }; + "/linked-products": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The church's other products + * @description As the Hub last listed them (with each heartbeat), with whether each is connected and its events shown here. + * + * **Who:** Admins only. + */ + get: operations["getLinked-products"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-products/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Publish my events (on or off) + * @description Whether this site publishes its public events for the church's other products (GET /api/feed/v1/events). + * + * **Who:** Admins only. + */ + put: operations["putLinked-productsSettings"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-products/{installId}/connect": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Connect to one of the church's products + * @description Sets up a signed link with it (crosscode.link/1). Both products must be in each other's list from the Hub. Connecting again replaces the link's secret. + * + * **Who:** Admins only. + */ + post: operations["postLinked-productsInstallIdConnect"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-products/{installId}/disconnect": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Disconnect a product + * @description Ends the link on both sides (the other product is told when it can be reached) and removes its events from this site. + * + * **Who:** Admins only. + */ + post: operations["postLinked-productsInstallIdDisconnect"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-products/{installId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Show events from a connected product (on or off) + * @description On: its events are fetched now and every 15 minutes, and shown on the public pages. Off: they are removed from this site. + * + * **Who:** Admins only. + */ + put: operations["putLinked-productsInstallId"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-products/{installId}/sync": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Fetch a product's events now + * @description **Who:** Admins only. + */ + post: operations["postLinked-productsInstallIdSync"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-events": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Upcoming events from the church's other products + * @description Read-only copies of the events of connected products shown here (Settings → Linked products), soonest first. Each links back to its own page. + * + * **Who:** Anyone. + */ + get: operations["getLinked-events"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/linked-events/{product}/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * One event from another of the church's products + * @description **Who:** Anyone. + */ + get: operations["getLinked-eventsProductId"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -8217,6 +8389,19 @@ export interface operations { } & { [key: string]: unknown; })[]; + /** @description The event as crosscode.event/1 (2.4.0), what its page builds its schema.org JSON-LD from (@crosscode/seo). The same shape the event feed publishes. */ + crosscodeEvent: ({ + /** @constant */ + schema: "crosscode.event/1"; + id: string; + } & { + [key: string]: unknown; + }) | null; + /** @description The lowest and highest current ticket prices in cents, for the JSON-LD price range (null when free) */ + priceRangeCents: { + lowCents: number; + highCents: number; + } | null; } & { [key: string]: unknown; }; @@ -38772,4 +38957,644 @@ export interface operations { }; }; }; + "getLinked-products": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + }; + }; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "putLinked-productsSettings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + publishEvents: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postLinked-productsInstallIdConnect": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The product's Hub install id */ + installId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postLinked-productsInstallIdDisconnect": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The product's Hub install id */ + installId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + otherSideTold: boolean; + problem: string | null; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "putLinked-productsInstallId": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The product's Hub install id */ + installId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + showEvents: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postLinked-productsInstallIdSync": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The product's Hub install id */ + installId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + hubConnected: boolean; + /** @description The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it */ + keyKnownToHub: boolean; + /** @description The Hub has a different key for this site (ask the provider to clear it) */ + keyMismatch: boolean; + publishEvents: boolean; + products: { + installId: string; + product: string; + name: string; + url: string; + /** @description In the list the Hub last gave (false: connected before, no longer listed) */ + listed: boolean; + publishesEvents: boolean; + /** @description null = not connected */ + link: { + /** Format: date-time */ + connectedAt: string; + /** @description Who pressed Connect here; null when the other product connected */ + connectedBy: string | null; + showEvents: boolean; + lastSyncAt: string | null; + /** @description When its events were last fetched successfully */ + lastGoodAt: string | null; + lastSyncError: string | null; + importedEvents: number; + } | null; + }[]; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "getLinked-events": { + parameters: { + query?: { + /** @description A campus slug (its events, church-wide ones and ones for a campus this site doesn't have), or 'all' for church-wide only */ + campus?: string; + /** @description How many per page */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + /** @description ":", unique across products */ + key: string; + product: string; + productName: string; + /** @description The event as crosscode.event/1, as the other product published it */ + event: { + /** @constant */ + schema: "crosscode.event/1"; + id: string; + title: string; + /** Format: date-time */ + startsAt: string; + /** Format: date-time */ + endsAt: string; + } & { + [key: string]: unknown; + }; + }[]; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "getLinked-eventsProductId": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The product the event comes from */ + product: "website" | "app"; + /** @description The event's id in that product */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + /** @description ":", unique across products */ + key: string; + product: string; + productName: string; + /** @description The event as crosscode.event/1, as the other product published it */ + event: { + /** @constant */ + schema: "crosscode.event/1"; + id: string; + title: string; + /** Format: date-time */ + startsAt: string; + /** Format: date-time */ + endsAt: string; + } & { + [key: string]: unknown; + }; + /** @description When the copy was last refreshed from its product */ + lastSyncedAt: string | null; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; } diff --git a/package-lock.json b/package-lock.json index 8842312..33385a7 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", @@ -108,6 +109,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 +143,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", @@ -6783,6 +6787,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", @@ -6796,6 +6809,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", @@ -6828,6 +6850,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", @@ -6904,6 +6935,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", @@ -6915,7 +6955,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": { @@ -6966,7 +7005,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" @@ -7041,6 +7079,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", @@ -7305,7 +7349,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": { @@ -8668,6 +8711,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", @@ -9278,6 +9331,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", @@ -9312,6 +9375,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", @@ -9473,6 +9576,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", @@ -9697,7 +9810,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": { @@ -9941,6 +10053,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", @@ -10284,6 +10409,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", @@ -10324,6 +10458,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", @@ -11277,6 +11424,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", @@ -11443,6 +11600,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", @@ -12422,6 +12585,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", @@ -12453,6 +12656,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", @@ -12656,6 +12869,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", @@ -12699,6 +12918,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", @@ -12875,6 +13118,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", @@ -12967,6 +13220,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", @@ -13026,6 +13289,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", @@ -14271,6 +14546,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", @@ -14394,6 +14679,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", @@ -14453,6 +14893,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", @@ -15365,6 +16268,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", @@ -16154,6 +17082,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", @@ -16500,6 +17438,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", @@ -16673,6 +17638,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", @@ -17537,6 +18535,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", @@ -17845,6 +18853,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", @@ -17931,6 +18953,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", @@ -18546,6 +19577,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", @@ -19031,6 +20082,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", @@ -19224,6 +20362,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", @@ -19654,6 +20820,16 @@ "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.4.0", diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 52a50fc..f2b0daa 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -7,6 +7,13 @@ "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "signing": [ + "./dist/signing.d.ts" + ] + } + }, "exports": { ".": { "import": { 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;