Publish my events: the Website's simple events as crosscode.event/1 (GET /api/feed/v1/events, updatedSince, removals in deleted for 90 days) and a signed event.changed to linked siblings. Show events from: each sibling's feed every 15 minutes and at once on its signed event.changed; read-only copies of only that sibling's events, one bad event skipped, the last good copy kept. Admin: Linked products. church.changed from Accounts refreshes the profile at once. Plan: the video hero, more blocks and more pages move to website@1.1.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
11 KiB
TypeScript
176 lines
11 KiB
TypeScript
import { after, describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import http from 'node:http';
|
|
import type { AddressInfo } from 'node:net';
|
|
import express from 'express';
|
|
import request from 'supertest';
|
|
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema, eventSchema } from '@crosscode/contracts';
|
|
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
|
import { hashToken } from '../src/lib/crypto.js';
|
|
import { buildFeed, syncLink } from '../src/feed/feed.js';
|
|
import { siteContent } from '../src/site/content.js';
|
|
import { publish } from '../src/site/snapshot.js';
|
|
import { harness, INSTALL_ID, SITE } from './support/harness.js';
|
|
|
|
const EVENTS_ID = '5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e';
|
|
const SECRET = 'events-link-secret-0123456789abcdef';
|
|
|
|
/** A Cross Events event, as its feed sends it. */
|
|
function ev(id: string, title: string, inDays: number, over: Record<string, unknown> = {}) {
|
|
const start = new Date(Date.now() + inDays * 864e5);
|
|
return {
|
|
schema: EVENT_SCHEMA, id, origin: { product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${id.slice(0, 4)}` },
|
|
status: 'published', updatedAt: new Date().toISOString(), title, summary: null, description: null, imageUrl: null, timezone: 'Africa/Johannesburg',
|
|
startsAt: start.toISOString(), endsAt: new Date(start.getTime() + 3600e3).toISOString(), allDay: false, sessions: [], location: { name: 'The hall', address: null, onlineUrl: null },
|
|
campus: null, series: null, tags: [], registration: { mode: 'origin', url: `https://events.hope.test/events/${id.slice(0, 4)}`, status: 'open', opensAt: null, closesAt: null, priceFrom: { amountCents: 45000, currency: 'ZAR' } },
|
|
...over,
|
|
};
|
|
}
|
|
|
|
/** A Cross Events site: serves whatever feed the test sets, and records what it's told. */
|
|
async function fakeEvents() {
|
|
const state = { feed: null as unknown, status: 200, asked: [] as string[], told: [] as { headers: http.IncomingHttpHeaders; body: string }[] };
|
|
const app = express();
|
|
app.get('/api/feed/v1/events', (req, res) => { state.asked.push(req.url); res.status(state.status).json(state.feed); });
|
|
app.post('/api/feed/v1/changed', express.text({ type: () => true }), (req, res) => { state.told.push({ headers: req.headers, body: req.body }); res.status(202).json({ accepted: true }); });
|
|
const server = http.createServer(app);
|
|
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
|
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
closers.push(() => new Promise((r) => server.close(r)));
|
|
return { url, state };
|
|
}
|
|
|
|
const closers: (() => Promise<unknown>)[] = [];
|
|
after(async () => { for (const c of closers) await c(); });
|
|
|
|
async function site() {
|
|
const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
|
const events = await fakeEvents();
|
|
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: events.url, publicKey: 'x', secret: h.ctx.secrets.encrypt(SECRET), connectedAt: new Date() } });
|
|
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000001', name: 'O', email: 'o@hope.test', role: 'owner' } });
|
|
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000001', expiresAt: new Date(Date.now() + 864e5) } });
|
|
await publish(h.ctx, { id: 'x', role: 'system' });
|
|
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
|
|
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
|
|
return b ? r.send(b) : r;
|
|
};
|
|
const link = async () => (await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } })) as unknown as Parameters<typeof syncLink>[1];
|
|
return { ...h, events, go, link };
|
|
}
|
|
|
|
describe('publishing the Website\'s events (Publish my events)', () => {
|
|
it('serves its published simple events as crosscode.event/1, removed ones as deleted', async () => {
|
|
const { go, app } = await site();
|
|
const start = new Date(Date.now() + 5 * 864e5).toISOString();
|
|
const a = (await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/p' })).body;
|
|
const b = (await go('post', '/events', { title: 'Carols', startsAt: start })).body;
|
|
await go('post', `/events/${a.id}/state`, { published: true });
|
|
await go('post', `/events/${b.id}/state`, { published: true });
|
|
const feed = (await request(app).get('/api/feed/v1/events')).body;
|
|
assert.ok(eventFeedSchema.safeParse(feed).success);
|
|
assert.equal(feed.events.length, 2);
|
|
const picnic = feed.events.find((e: { title: string }) => e.title === 'Picnic');
|
|
assert.ok(eventSchema.safeParse(picnic).success);
|
|
assert.deepEqual(picnic.origin, { product: 'website', installId: INSTALL_ID, url: `${SITE}/events/picnic` });
|
|
assert.deepEqual([picnic.registration.mode, picnic.registration.url], ['external', 'https://forms.example/p']);
|
|
|
|
const before = new Date().toISOString();
|
|
await go('post', `/events/${b.id}/state`, { published: false });
|
|
const since = (await request(app).get(`/api/feed/v1/events?updatedSince=${encodeURIComponent(before)}`)).body;
|
|
assert.deepEqual(since.deleted.map((d: { id: string }) => d.id), [b.id]);
|
|
assert.equal(since.events.length, 0, 'nothing else changed since');
|
|
assert.equal((await request(app).get('/api/feed/v1/events?updatedSince=nonsense')).status, 400);
|
|
|
|
await go('put', '/feed', { publish: false });
|
|
assert.equal((await request(app).get('/api/feed/v1/events')).status, 404);
|
|
});
|
|
|
|
it('tells the church\'s Events, signed, when one of its events changes', async () => {
|
|
const { go, events } = await site();
|
|
const e = (await go('post', '/events', { title: 'Picnic', startsAt: new Date(Date.now() + 864e5).toISOString() })).body;
|
|
await go('post', `/events/${e.id}/state`, { published: true });
|
|
await new Promise((r) => setTimeout(r, 200));
|
|
const told = events.state.told.at(-1)!;
|
|
assert.equal(told.headers[LINK_HEADERS.sender], INSTALL_ID);
|
|
assert.deepEqual(JSON.parse(told.body).eventIds, [e.id]);
|
|
});
|
|
});
|
|
|
|
describe('showing events from Cross Events (Show events from)', () => {
|
|
it('imports only its own, valid events; they show on the site and link back to Events', async () => {
|
|
const { ctx, events, link, db } = await site();
|
|
events.state.feed = {
|
|
schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [],
|
|
events: [
|
|
ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10),
|
|
ev('7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a', 'From someone else', 4, { origin: { product: 'events', installId: '00000000-0000-4000-8000-0000000000ff', url: 'https://other.test/e' } }),
|
|
{ ...ev('8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b', 'Broken', 3), startsAt: 'not a date' },
|
|
],
|
|
};
|
|
const r = await syncLink(ctx, await link());
|
|
assert.deepEqual([r.ok, r.imported, r.rejected], [true, 1, 1]);
|
|
const c = await siteContent(ctx);
|
|
assert.equal(c.mode === 'published' && c.events.length, 1);
|
|
if (c.mode === 'published') {
|
|
assert.equal(c.events[0]!.title, 'Youth camp');
|
|
assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d');
|
|
assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 });
|
|
}
|
|
assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/);
|
|
});
|
|
|
|
it('asks only for what changed next time, drops deleted ones, and keeps the last good copy when Events is down', async () => {
|
|
const { ctx, events, link, db } = await site();
|
|
const id = '6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f';
|
|
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev(id, 'Youth camp', 10)] };
|
|
await syncLink(ctx, await link());
|
|
events.state.status = 503;
|
|
const down = await syncLink(ctx, await link());
|
|
assert.equal(down.ok, false);
|
|
assert.equal(await db.importedEvent.count(), 1, 'the last good copy stays');
|
|
assert.match(events.state.asked.at(-1)!, /updatedSince=/);
|
|
events.state.status = 200;
|
|
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [{ id, deletedAt: new Date().toISOString() }], events: [] };
|
|
await syncLink(ctx, await link());
|
|
assert.equal(await db.importedEvent.count(), 0);
|
|
});
|
|
|
|
it('switching Show events off removes its events; a signed event.changed fetches at once', async () => {
|
|
const { ctx, events, link, db, go, app } = await site();
|
|
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10)] };
|
|
await syncLink(ctx, await link());
|
|
await go('put', `/links/${EVENTS_ID}`, { showEvents: false });
|
|
assert.equal(await db.importedEvent.count(), 0);
|
|
await go('put', `/links/${EVENTS_ID}`, { showEvents: true });
|
|
assert.equal(await db.importedEvent.count(), 1);
|
|
|
|
const body = JSON.stringify({ schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [] });
|
|
const asked = events.state.asked.length;
|
|
const ok = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: SECRET, rawBody: body })).set('Content-Type', 'application/json').send(body);
|
|
assert.equal(ok.status, 202);
|
|
await new Promise((r) => setTimeout(r, 200));
|
|
assert.equal(events.state.asked.length, asked + 1);
|
|
const forged = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: 'wrong-secret-0123456789abcdefghij', rawBody: body })).set('Content-Type', 'application/json').send(body);
|
|
assert.equal(forged.status, 401);
|
|
const links = (await go('get', '/links')).body;
|
|
assert.equal(links.products.find((p: { product: string }) => p.product === 'events').events, 1);
|
|
});
|
|
|
|
it('takes church.changed only from Accounts, signed', async () => {
|
|
const { app, db, ctx } = await site();
|
|
const accounts = (await db.productLink.findFirst({ where: { product: 'accounts' } }))!;
|
|
const body = JSON.stringify({ schema: 'crosscode.church/1', type: 'church.changed', occurredAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
|
|
const send = (sender: string, secret: string) => request(app).post('/api/church/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: sender, secret, rawBody: body })).set('Content-Type', 'application/json').send(body);
|
|
assert.equal((await send(String(accounts.installId), ctx.secrets.decrypt(String(accounts.secret)))).status, 202);
|
|
assert.equal((await send(EVENTS_ID, SECRET)).status, 404, 'Events isn\'t Accounts');
|
|
});
|
|
});
|
|
|
|
describe('the feed builder', () => {
|
|
it('leaves out events that ended over 30 days ago', async () => {
|
|
const { ctx, db } = await site();
|
|
await db.simpleEvent.create({ data: { slug: 'old', title: 'Old', startsAt: new Date(Date.now() - 40 * 864e5), publishedAt: new Date() } });
|
|
assert.equal((await buildFeed(ctx, null)).events.length, 0);
|
|
});
|
|
});
|