Events 2.4.0 backend: protocol v2, Linked products, the event feed
- Hub client: register and heartbeat on protocol v2 with the site's Ed25519 key (sent on the heartbeat until the Hub has it); falls back to v1 for a day if the Hub refuses v2, so the licence always refreshes. - crosscode.link/1 Connect / Disconnect, both directions, trusted through the Hub's cached linkedProducts (ProductLink, LinkNonce). - GET /api/feed/v1/events from FeedEntry (go-live, closing and selling out are changes; deactivated events go in deleted), event.changed to connected products, and showing their events (ImportedEvent). - /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains crosscodeEvent and priceRangeCents for the JSON-LD. - Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ const mockSettings = new Map();
|
||||
jest.mock('../src/config/db', () => ({
|
||||
appSetting: {
|
||||
findMany: jest.fn(async ({ where }) => [...mockSettings].filter(([key]) => where.key.in.includes(key)).map(([key, value]) => ({ key, value }))),
|
||||
findUnique: jest.fn(async ({ where }) => (mockSettings.has(where.key) ? { key: where.key, value: mockSettings.get(where.key) } : null)),
|
||||
upsert: jest.fn(async ({ where, create }) => { mockSettings.set(where.key, create.value); }),
|
||||
deleteMany: jest.fn(async ({ where }) => { mockSettings.delete(where.key); }),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
// 2.4.0 (docs/EVENTS-2.4-PLAN.md §8): the event feed, Linked products / Connect, showing events
|
||||
// from linked products, and the v2 heartbeat. In-memory database (tests/support/fakeFeedDb.js).
|
||||
jest.mock('../src/config/db', () => require('./support/fakeFeedDb'));
|
||||
jest.mock('../src/utils/settingsCache', () => {
|
||||
const db = require('./support/fakeFeedDb');
|
||||
return {
|
||||
getSetting: async (key, fallback = '') => (db.t.appSetting.get(key)?.value ?? fallback),
|
||||
getSettingSync: () => '',
|
||||
invalidate: () => {},
|
||||
warmCache: async () => {},
|
||||
ENCRYPTED_KEYS: new Set(),
|
||||
};
|
||||
});
|
||||
const mockSold = new Map();
|
||||
jest.mock('../src/utils/stock', () => ({ takenCount: async ({ eventOptionId, sessionId }) => mockSold.get(sessionId ? `${eventOptionId}:${sessionId}` : eventOptionId) || 0 }));
|
||||
const mockTasks = [];
|
||||
jest.mock('../src/jobs', () => ({ enqueueTask: async (name, data) => { mockTasks.push([name, data]); return { queued: true }; } }));
|
||||
|
||||
process.env.WEBHOOKS_ALLOW_PRIVATE = 'true';
|
||||
process.env.FRONTEND_URL = 'https://events.hope.test';
|
||||
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
|
||||
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const { eventSchema, eventFeedSchema, linkConnectSchema, hub: hubContract } = require('@crosscode/contracts');
|
||||
const signing = require('@crosscode/contracts/signing');
|
||||
const db = require('./support/fakeFeedDb');
|
||||
const path = require('path');
|
||||
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
|
||||
const contractSample = (name) => JSON.parse(require('fs').readFileSync(path.join(SAMPLES, name), 'utf8'));
|
||||
const { encrypt } = require('../src/utils/encryption');
|
||||
const { buildCrosscodeEvent, plainToMarkdown, absolute } = require('../src/feed/build');
|
||||
const { refreshFeed, feedResponse } = require('../src/feed/entries');
|
||||
const { syncLink } = require('../src/feed/sync');
|
||||
const connect = require('../src/links/connect');
|
||||
const store = require('../src/links/store');
|
||||
const { crossProductRouter } = require('../src/links/routes');
|
||||
|
||||
const EVENTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||
const WEBSITE_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
||||
const WEBSITE_URL = 'https://www.hope.test';
|
||||
const NOW = new Date('2026-11-20T10:00:00.000Z');
|
||||
const DAY = 24 * 3600e3;
|
||||
|
||||
const ctx = (over = {}) => ({ installId: EVENTS_ID, baseUrl: 'https://events.hope.test', timezone: 'Africa/Johannesburg', campusesOn: false, now: NOW, ...over });
|
||||
|
||||
let n = 0;
|
||||
const uuid = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`;
|
||||
|
||||
function eventRow(over = {}) {
|
||||
const id = over.id || uuid();
|
||||
return {
|
||||
id,
|
||||
title: 'Youth Camp',
|
||||
description: 'Three days away.\nBring a *sleeping bag*.',
|
||||
startDate: new Date(NOW.getTime() + 30 * DAY),
|
||||
endDate: new Date(NOW.getTime() + 32 * DAY),
|
||||
goLiveAt: new Date(NOW.getTime() - DAY),
|
||||
registrationDeadline: null,
|
||||
picture: '/uploads/camp.jpg',
|
||||
location: 'Camp Wartburg',
|
||||
requiresRegistration: true,
|
||||
waitlistEnabled: false,
|
||||
scheduleType: 'single',
|
||||
attendanceMode: 'whole',
|
||||
lateJoinEnabled: false,
|
||||
lateJoinUntilSessionId: null,
|
||||
kidsOptionId: null,
|
||||
volunteerOptionId: null,
|
||||
isActive: true,
|
||||
isHidden: false,
|
||||
campus: null,
|
||||
series: null,
|
||||
sessions: [],
|
||||
eventOptions: [
|
||||
{ id: `${id}-adult`, price: 450, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||
{ id: `${id}-child`, price: 300, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||
{ id: `${id}-tshirt`, price: 120, isMainTicket: false, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||
],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const keys = { events: signing.generateEd25519(), website: signing.generateEd25519() };
|
||||
const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
|
||||
|
||||
async function setUpSite({ linked = true } = {}) {
|
||||
db.reset();
|
||||
store.forgetKeyPair();
|
||||
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
|
||||
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
|
||||
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
|
||||
if (linked) await store.saveLinkedProducts([{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }]);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
mockSold.clear();
|
||||
mockTasks.length = 0;
|
||||
await setUpSite();
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
// ─── Building crosscode.event/1 ───────────────────────────────────────────────
|
||||
|
||||
describe('crosscode.event/1 from an event', () => {
|
||||
test('a ticketed event passes the contract, with the lowest main ticket as the price', () => {
|
||||
const { event, priceRangeCents } = buildCrosscodeEvent(eventRow(), new Map(), ctx());
|
||||
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
|
||||
expect(event.origin).toEqual({ product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${event.id}` });
|
||||
expect(event.registration).toMatchObject({ mode: 'origin', status: 'open', priceFrom: { amountCents: 30000, currency: 'ZAR' } });
|
||||
expect(priceRangeCents).toEqual({ lowCents: 30000, highCents: 45000 });
|
||||
expect(event.imageUrl).toBe('https://events.hope.test/api/uploads/camp.jpg');
|
||||
expect(event.location).toEqual({ name: 'Camp Wartburg', address: null, onlineUrl: null });
|
||||
});
|
||||
|
||||
test('never carries the contact person, kids or volunteer tickets', () => {
|
||||
const row = eventRow({ contactName: 'Jane', contactPhone: '082', contactEmail: 'jane@x.co.za' });
|
||||
row.kidsOptionId = row.eventOptions[1].id;
|
||||
row.eventOptions[1].price = 0;
|
||||
const json = JSON.stringify(buildCrosscodeEvent(row, new Map(), ctx()).event);
|
||||
expect(json).not.toMatch(/Jane|082|jane@/);
|
||||
expect(buildCrosscodeEvent(row, new Map(), ctx()).event.registration.priceFrom).toEqual({ amountCents: 45000, currency: 'ZAR' });
|
||||
});
|
||||
|
||||
test.each([
|
||||
['not_open', { goLiveAt: new Date(NOW.getTime() + DAY) }, new Map()],
|
||||
['closed', { registrationDeadline: new Date(NOW.getTime() - 3600e3) }, new Map()],
|
||||
])('registration %s', (status, over, avail) => {
|
||||
expect(buildCrosscodeEvent(eventRow(over), avail, ctx()).event.registration.status).toBe(status);
|
||||
});
|
||||
|
||||
test('full when every main ticket is limited and sold out; waitlist when it has one', () => {
|
||||
const row = eventRow();
|
||||
row.eventOptions[0].stockLimit = 10;
|
||||
row.eventOptions[1].stockLimit = 5;
|
||||
const soldOut = new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 0]]);
|
||||
expect(buildCrosscodeEvent(row, soldOut, ctx()).event.registration.status).toBe('full');
|
||||
expect(buildCrosscodeEvent({ ...row, waitlistEnabled: true }, soldOut, ctx()).event.registration.status).toBe('waitlist');
|
||||
// One main ticket still has places: open.
|
||||
expect(buildCrosscodeEvent(row, new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 2]]), ctx()).event.registration.status).toBe('open');
|
||||
});
|
||||
|
||||
test('contact-only and free events', () => {
|
||||
expect(buildCrosscodeEvent(eventRow({ requiresRegistration: false }), new Map(), ctx()).event.registration).toEqual({ mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null });
|
||||
const free = eventRow();
|
||||
for (const o of free.eventOptions) o.price = 0;
|
||||
const built = buildCrosscodeEvent(free, new Map(), ctx());
|
||||
expect(built.event.registration.priceFrom).toBeNull();
|
||||
expect(built.priceRangeCents).toBeNull();
|
||||
});
|
||||
|
||||
test('a multi-day event: sessions, and start/end from the sessions that still run', () => {
|
||||
const s = (d, cancelled = false) => ({ id: uuid(), label: `Week ${d}`, startsAt: new Date(NOW.getTime() + d * 7 * DAY), endsAt: new Date(NOW.getTime() + d * 7 * DAY + 2 * 3600e3), location: null, cancelledAt: cancelled ? NOW : null });
|
||||
const sessions = [s(1), s(2), s(3, true)];
|
||||
const { event } = buildCrosscodeEvent(eventRow({ scheduleType: 'sessions', sessions }), new Map(), ctx());
|
||||
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
|
||||
expect(event.sessions).toHaveLength(3);
|
||||
expect(event.endsAt).toBe(sessions[1].endsAt.toISOString());
|
||||
});
|
||||
|
||||
test('an online event, and the campus only while campuses are on', () => {
|
||||
const row = eventRow({ location: 'https://youtube.com/live/abc', campus: { slug: 'meyerton', name: 'Meyerton' } });
|
||||
expect(buildCrosscodeEvent(row, new Map(), ctx()).event).toMatchObject({ location: { onlineUrl: 'https://youtube.com/live/abc' }, campus: null });
|
||||
expect(buildCrosscodeEvent(row, new Map(), ctx({ campusesOn: true })).event.campus).toEqual({ slug: 'meyerton', name: 'Meyerton' });
|
||||
});
|
||||
|
||||
test('plain text descriptions read the same as markdown', () => {
|
||||
expect(plainToMarkdown('Bring a *sleeping bag*\n- not a list\n1. not numbered\n\n# not a heading')).toBe('Bring a \\*sleeping bag\\* \n\\- not a list \n1\\. not numbered\n\n\\# not a heading');
|
||||
expect(plainToMarkdown(' ')).toBeNull();
|
||||
expect(absolute('https://e.test', 'https://cdn.test/x.jpg')).toBe('https://cdn.test/x.jpg');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── The published feed ───────────────────────────────────────────────────────
|
||||
|
||||
describe('the feed', () => {
|
||||
const put = (row) => db.t.event.set(row.id, row);
|
||||
|
||||
test('publishes public events, and updatedSince returns exactly what changed', async () => {
|
||||
const a = eventRow();
|
||||
const hidden = eventRow({ isHidden: true });
|
||||
const later = eventRow({ goLiveAt: new Date(NOW.getTime() + 2 * 3600e3) });
|
||||
[a, hidden, later].forEach(put);
|
||||
|
||||
const first = await refreshFeed(NOW);
|
||||
expect(first.changed).toEqual([a.id]);
|
||||
const full = await feedResponse(null, NOW);
|
||||
expect(eventFeedSchema.safeParse(full).success).toBe(true);
|
||||
expect(full.events.map((e) => e.id)).toEqual([a.id]);
|
||||
|
||||
// Nothing changed: nothing new since.
|
||||
const t1 = new Date(NOW.getTime() + 60e3);
|
||||
expect((await refreshFeed(t1)).changed).toEqual([]);
|
||||
expect((await feedResponse(NOW, t1)).events).toEqual([]);
|
||||
|
||||
// Going live changes no Event row, but shows up.
|
||||
const t2 = new Date(NOW.getTime() + 3 * 3600e3);
|
||||
expect((await refreshFeed(t2)).changed).toEqual([later.id]);
|
||||
expect((await feedResponse(t1, t2)).events.map((e) => e.id)).toEqual([later.id]);
|
||||
});
|
||||
|
||||
test('selling out is a change; deactivating puts the event in deleted', async () => {
|
||||
const a = eventRow();
|
||||
a.eventOptions[0].stockLimit = 2;
|
||||
a.eventOptions[1].stockLimit = 2;
|
||||
put(a);
|
||||
await refreshFeed(NOW);
|
||||
|
||||
mockSold.set(a.eventOptions[0].id, 2);
|
||||
mockSold.set(a.eventOptions[1].id, 2);
|
||||
const t1 = new Date(NOW.getTime() + 60e3);
|
||||
expect((await refreshFeed(t1)).changed).toEqual([a.id]);
|
||||
const after = await feedResponse(NOW, t1);
|
||||
expect(after.events[0].registration.status).toBe('full');
|
||||
expect(after.events[0].updatedAt).toBe(t1.toISOString());
|
||||
|
||||
put({ ...a, isActive: false });
|
||||
const t2 = new Date(NOW.getTime() + 120e3);
|
||||
expect((await refreshFeed(t2)).removed).toEqual([a.id]);
|
||||
const gone = await feedResponse(t1, t2);
|
||||
expect(gone.events).toEqual([]);
|
||||
expect(gone.deleted).toEqual([{ id: a.id, deletedAt: t2.toISOString() }]);
|
||||
// A full fetch no longer lists it.
|
||||
expect((await feedResponse(null, t2)).events).toEqual([]);
|
||||
});
|
||||
|
||||
test('an event that ended a month ago drops out quietly (not deleted)', async () => {
|
||||
const a = eventRow({ startDate: new Date(NOW.getTime() - 2 * DAY), endDate: new Date(NOW.getTime() - DAY) });
|
||||
put(a);
|
||||
await refreshFeed(NOW);
|
||||
const later = new Date(NOW.getTime() + 31 * DAY);
|
||||
const r = await refreshFeed(later);
|
||||
expect(r.removed).toEqual([]);
|
||||
expect((await feedResponse(NOW, later)).deleted).toEqual([]);
|
||||
expect(db.t.feedEntry.has(a.id)).toBe(false);
|
||||
});
|
||||
|
||||
test('without a Hub install id there is no feed', async () => {
|
||||
db.t.appSetting.delete('hub_install_id');
|
||||
put(eventRow());
|
||||
expect(await refreshFeed(NOW)).toEqual({ changed: [], removed: [], skipped: [] });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Connect ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function connectMessage(over = {}, key = keys.website) {
|
||||
return signing.signLink({
|
||||
schema: 'crosscode.link/1',
|
||||
type: 'link.connect',
|
||||
from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL },
|
||||
to: { installId: EVENTS_ID },
|
||||
secret: signing.newLinkSecret(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
nonce: signing.newLinkNonce(),
|
||||
...over,
|
||||
}, key.privateKeyPem);
|
||||
}
|
||||
|
||||
describe('Connect from a linked product', () => {
|
||||
test('a listed product connects; the reply is signed with this site\'s key and echoes the nonce', async () => {
|
||||
const m = connectMessage();
|
||||
const reply = await connect.acceptConnect(m, '1.2.3.4');
|
||||
expect(signing.verifyLink(reply, pem(keys.events))).toEqual({ ok: true });
|
||||
expect(reply).toMatchObject({ type: 'link.connected', inReplyTo: m.nonce, to: { installId: WEBSITE_ID }, from: { product: 'events', installId: EVENTS_ID } });
|
||||
const link = db.t.productLink.get(WEBSITE_ID);
|
||||
expect(link).toMatchObject({ product: 'website', url: WEBSITE_URL, connectedById: null });
|
||||
expect(db.t.audit.map((a) => a.action)).toEqual(['product_link_connected']);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['not listed by the Hub', async () => { await store.saveLinkedProducts([]); return connectMessage(); }, 'NOT_LINKED'],
|
||||
['signed with another key', async () => connectMessage({}, signing.generateEd25519()), 'BAD_SIGNATURE'],
|
||||
['too old', async () => connectMessage({ issuedAt: new Date(Date.now() - 10 * 60e3).toISOString() }), 'STALE_REQUEST'],
|
||||
['for another install', async () => connectMessage({ to: { installId: WEBSITE_ID } }), 'WRONG_INSTALL'],
|
||||
['claiming another product', async () => connectMessage({ from: { product: 'app', installId: WEBSITE_ID, url: WEBSITE_URL } }), 'NOT_LINKED'],
|
||||
['not a link message', async () => ({ hello: 'world' }), 'INVALID_REQUEST'],
|
||||
])('refused when %s', async (_name, make, code) => {
|
||||
await expect(connect.acceptConnect(await make(), null)).rejects.toMatchObject({ code });
|
||||
expect(db.t.productLink.size).toBe(0);
|
||||
});
|
||||
|
||||
test('a replayed message is refused', async () => {
|
||||
const m = connectMessage();
|
||||
await connect.acceptConnect(m, null);
|
||||
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
|
||||
});
|
||||
|
||||
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
|
||||
await connect.acceptConnect(connectMessage(), null);
|
||||
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
|
||||
const msg = (key) => signing.signLink({ schema: 'crosscode.link/1', type: 'link.disconnect', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce() }, key.privateKeyPem);
|
||||
await expect(connect.acceptDisconnect(msg(signing.generateEd25519()), null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
|
||||
await connect.acceptDisconnect(msg(keys.website), null);
|
||||
expect(db.t.productLink.size).toBe(0);
|
||||
expect(db.t.importedEvent.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Connect from this site', () => {
|
||||
const admin = { id: 'admin-1', role: 'admin' };
|
||||
|
||||
function siblingAnswers(make) {
|
||||
global.fetch = jest.fn(async (url, init) => {
|
||||
const body = JSON.parse(init.body);
|
||||
expect(String(url)).toBe(`${WEBSITE_URL}/api/links/v1/connect`);
|
||||
expect(linkConnectSchema.safeParse(body).success).toBe(true);
|
||||
expect(signing.verifyLink(body, pem(keys.events))).toEqual({ ok: true });
|
||||
const reply = make(body);
|
||||
return new Response(JSON.stringify(reply.body), { status: reply.status || 200, headers: { 'content-type': 'application/json' } });
|
||||
});
|
||||
}
|
||||
const goodReply = (body, key = keys.website, over = {}) => ({
|
||||
body: signing.signLink({ schema: 'crosscode.link/1', type: 'link.connected', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, inReplyTo: body.nonce, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce(), ...over }, key.privateKeyPem),
|
||||
});
|
||||
|
||||
test('connects when the sibling answers, signed with its listed key', async () => {
|
||||
let sentSecret;
|
||||
siblingAnswers((body) => { sentSecret = body.secret; return goodReply(body); });
|
||||
await connect.connectTo(WEBSITE_ID, admin, null);
|
||||
const link = db.t.productLink.get(WEBSITE_ID);
|
||||
expect(link.connectedById).toBe('admin-1');
|
||||
expect(require('../src/utils/encryption').decrypt(link.secret)).toBe(sentSecret);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['signed with another key', (body) => goodReply(body, signing.generateEd25519())],
|
||||
['for another message', (body) => goodReply(body, keys.website, { inReplyTo: signing.newLinkNonce() })],
|
||||
])('refuses an answer %s', async (_name, make) => {
|
||||
siblingAnswers(make);
|
||||
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
|
||||
expect(db.t.productLink.size).toBe(0);
|
||||
});
|
||||
|
||||
test('passes on the sibling\'s refusal', async () => {
|
||||
siblingAnswers(() => ({ status: 403, body: { message: 'Not linked yet', code: 'NOT_LINKED' } }));
|
||||
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
|
||||
});
|
||||
|
||||
test('only to a product the Hub listed', async () => {
|
||||
await expect(connect.connectTo('3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09', admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Showing events from a linked product ──────────────────────────────────────
|
||||
|
||||
describe('events from a linked product', () => {
|
||||
const sample = () => contractSample('event-simple.json');
|
||||
const linkRow = () => ({ installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('s'), connectedAt: NOW, connectedById: null, showEvents: true, lastSyncAt: null, lastGoodAt: null, lastSyncError: null });
|
||||
const feedOf = (events, deleted = []) => ({ schema: 'crosscode.event-feed/1', generatedAt: NOW.toISOString(), events, deleted });
|
||||
const answer = (body, status = 200) => { global.fetch = jest.fn(async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); };
|
||||
|
||||
test('imports its events, skips a bad one and one that claims another origin', async () => {
|
||||
db.t.productLink.set(WEBSITE_ID, linkRow());
|
||||
const good = sample();
|
||||
const bad = { ...sample(), id: 'not-a-uuid' };
|
||||
const spoofed = { ...sample(), id: uuid(), origin: { ...sample().origin, installId: EVENTS_ID } };
|
||||
answer(feedOf([good, bad, spoofed]));
|
||||
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||
expect(r).toMatchObject({ ok: true, imported: 1, rejected: 1, skipped: 1 });
|
||||
expect([...db.t.importedEvent.keys()]).toEqual([`website:${good.id}`]);
|
||||
expect(String(global.fetch.mock.calls[0][0])).toBe(`${WEBSITE_URL}/api/feed/v1/events`);
|
||||
expect(db.t.productLink.get(WEBSITE_ID).lastGoodAt.toISOString()).toBe(NOW.toISOString());
|
||||
});
|
||||
|
||||
test('a source that is down keeps its last events and shows the error', async () => {
|
||||
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
|
||||
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
|
||||
global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); });
|
||||
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(db.t.importedEvent.size).toBe(1);
|
||||
expect(db.t.productLink.get(WEBSITE_ID).lastSyncError).toMatch(/could not be reached/);
|
||||
// It fetched what changed since a little before the last good fetch.
|
||||
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
|
||||
});
|
||||
|
||||
test('deleted events go; never re-published in this site\'s own feed', async () => {
|
||||
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
|
||||
const e = sample();
|
||||
answer(feedOf([e]));
|
||||
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||
answer(feedOf([], [{ id: e.id, deletedAt: NOW.toISOString() }]));
|
||||
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||
expect(db.t.importedEvent.size).toBe(0);
|
||||
// The feed is built from this site's own events only.
|
||||
db.t.importedEvent.set('website:y', { key: 'website:y', linkId: WEBSITE_ID, payload: e });
|
||||
await refreshFeed(NOW);
|
||||
expect((await feedResponse(null, NOW)).events).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── The endpoints other products call ─────────────────────────────────────────
|
||||
|
||||
describe('/api/feed/v1 and /api/links/v1', () => {
|
||||
const app = () => express().use('/api', crossProductRouter());
|
||||
|
||||
test('the feed: on by default, 404 when publishing is off, 400 for a bad updatedSince', async () => {
|
||||
// The route works on the real clock.
|
||||
const now = Date.now();
|
||||
db.t.event.set('e', eventRow({ id: uuid(), goLiveAt: new Date(now - DAY), startDate: new Date(now + 10 * DAY), endDate: new Date(now + 11 * DAY) }));
|
||||
await refreshFeed(new Date());
|
||||
const res = await request(app()).get('/api/feed/v1/events');
|
||||
expect(res.status).toBe(200);
|
||||
expect(eventFeedSchema.safeParse(res.body).success).toBe(true);
|
||||
expect(res.body.events).toHaveLength(1);
|
||||
expect((await request(app()).get('/api/feed/v1/events?updatedSince=yesterday')).body.code).toBe('INVALID_REQUEST');
|
||||
db.t.appSetting.set('feed_publish', { key: 'feed_publish', value: 'false' });
|
||||
expect((await request(app()).get('/api/feed/v1/events')).status).toBe(404);
|
||||
});
|
||||
|
||||
test('event.changed: checked with the link\'s secret, then a fetch is queued', async () => {
|
||||
db.t.productLink.set(WEBSITE_ID, { installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('link-secret'), connectedAt: NOW, showEvents: true });
|
||||
const body = JSON.stringify({ schema: 'crosscode.event-feed/1', type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [uuid()] });
|
||||
const send = (secret, sender = WEBSITE_ID) => request(app()).post('/api/feed/v1/changed').set('Content-Type', 'application/json')
|
||||
.set(signing.signedHeaders(signing.LINK_HEADERS, { senderId: sender, secret, rawBody: body })).send(body);
|
||||
expect((await send('wrong')).status).toBe(401);
|
||||
expect((await send('link-secret', '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09')).status).toBe(404);
|
||||
const ok = await send('link-secret');
|
||||
expect(ok.status).toBe(202);
|
||||
expect(mockTasks).toEqual([['feed-sync-link', { installId: WEBSITE_ID }]]);
|
||||
});
|
||||
|
||||
test('connect over HTTP, and errors as { message, code }', async () => {
|
||||
const res = await request(app()).post('/api/links/v1/connect').send(connectMessage());
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.type).toBe('link.connected');
|
||||
const bad = await request(app()).post('/api/links/v1/connect').send(connectMessage({}, signing.generateEd25519()));
|
||||
expect(bad.status).toBe(401);
|
||||
expect(bad.body).toEqual({ message: expect.any(String), code: 'BAD_SIGNATURE' });
|
||||
const notJson = await request(app()).post('/api/links/v1/connect').set('Content-Type', 'application/json').send('{oops');
|
||||
expect(notJson.body.code).toBe('INVALID_REQUEST');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── The v2 heartbeat ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('protocol v2 heartbeat', () => {
|
||||
const report = require('../src/hub/report');
|
||||
const sampleHb = contractSample('hub-heartbeat-events.json');
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(report, 'health').mockResolvedValue({ ...sampleHb.health, jobs: null, pendingMigrations: null });
|
||||
jest.spyOn(report, 'stats').mockResolvedValue(sampleHb.stats);
|
||||
});
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
test('fits the contract (gaps in health filled), with the public key until the Hub has it', async () => {
|
||||
const client = require('../src/hub/client');
|
||||
const { body, v2 } = await client.heartbeatBody();
|
||||
expect(v2).toBe(true);
|
||||
expect(hubContract.heartbeatRequestSchema.safeParse(body).error?.issues ?? []).toEqual([]);
|
||||
expect(body.publicKey).toBe(pem(keys.events));
|
||||
await store.setPublicKeyStatus('saved');
|
||||
expect((await client.heartbeatBody()).body).not.toHaveProperty('publicKey');
|
||||
await store.setPublicKeyStatus('mismatch');
|
||||
expect((await client.heartbeatBody()).body.publicKey).toBe(pem(keys.events));
|
||||
});
|
||||
|
||||
test('a Hub that refuses v2 gets the same heartbeat as v1, and v1 for a day', async () => {
|
||||
const client = require('../src/hub/client');
|
||||
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
|
||||
const sent = [];
|
||||
global.fetch = jest.fn(async (_url, init) => {
|
||||
const b = JSON.parse(init.body);
|
||||
sent.push(b.protocolVersion);
|
||||
if (b.protocolVersion === 2) return new Response(JSON.stringify({ message: 'Protocol 2 is not supported', code: 'UNSUPPORTED_PROTOCOL' }), { status: 400 });
|
||||
return new Response(JSON.stringify({ licence: 'x', latestVersion: null }), { status: 200 });
|
||||
});
|
||||
const r = await client.heartbeat();
|
||||
expect(r).toMatchObject({ ok: true, protocol: 1 });
|
||||
expect(sent).toEqual([2, 1]);
|
||||
await client.heartbeat();
|
||||
expect(sent).toEqual([2, 1, 1]);
|
||||
});
|
||||
|
||||
test('saves the church\'s other products from the reply', async () => {
|
||||
const client = require('../src/hub/client');
|
||||
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
|
||||
const listed = [{ product: 'app', installId: '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04', url: 'https://app.hope.test', publicKey: pem(keys.website) }, { product: 'bogus' }];
|
||||
global.fetch = jest.fn(async () => new Response(JSON.stringify({ licence: 'x', latestVersion: null, linkedProducts: listed, publicKeyStatus: 'saved' }), { status: 200 }));
|
||||
await client.heartbeat();
|
||||
expect((await store.linkedProducts()).map((l) => l.product)).toEqual(['app']);
|
||||
expect(await store.publicKeyStatus()).toBe('saved');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
// An in-memory stand-in for the Prisma client, with just what the feed and Linked products use
|
||||
// (src/feed, src/links, src/v2/resources/linkedProducts.ts). Where clauses are matched generically
|
||||
// (AND, equality, in / notIn, gt / gte / lt / lte, not, nested relation filters on `link`).
|
||||
|
||||
const t = { appSetting: new Map(), productLink: new Map(), linkNonce: new Map(), importedEvent: new Map(), feedEntry: new Map(), event: new Map(), campus: [], user: [], audit: [] };
|
||||
|
||||
// Rows keep their Dates; JSON columns (payload) keep their strings, as Prisma gives them back.
|
||||
const clone = (v) => (v === undefined ? v : structuredClone(v));
|
||||
const val = (v) => (v instanceof Date ? v.getTime() : v);
|
||||
|
||||
function matchValue(actual, cond) {
|
||||
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||
return Object.entries(cond).every(([op, x]) => {
|
||||
switch (op) {
|
||||
case 'in': return x.includes(actual);
|
||||
case 'notIn': return !x.includes(actual);
|
||||
case 'gt': return actual != null && val(actual) > val(x);
|
||||
case 'gte': return actual != null && val(actual) >= val(x);
|
||||
case 'lt': return actual != null && val(actual) < val(x);
|
||||
case 'lte': return actual != null && val(actual) <= val(x);
|
||||
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||
default: throw new Error(`fakeFeedDb: no operator ${op}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
return val(actual) === val(cond);
|
||||
}
|
||||
|
||||
function matches(row, where = {}) {
|
||||
return Object.entries(where || {}).every(([k, cond]) => {
|
||||
if (k === 'AND') return cond.every((w) => matches(row, w));
|
||||
if (k === 'link') return matches(t.productLink.get(row.linkId) || {}, cond.is || cond);
|
||||
return matchValue(row[k], cond);
|
||||
});
|
||||
}
|
||||
|
||||
const pick = (row, select) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||
|
||||
function sortBy(rows, orderBy) {
|
||||
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||
return [...rows].sort((a, b) => {
|
||||
for (const o of list) {
|
||||
const [k, dir] = Object.entries(o)[0];
|
||||
const d = val(a[k]) < val(b[k]) ? -1 : val(a[k]) > val(b[k]) ? 1 : 0;
|
||||
if (d) return dir === 'desc' ? -d : d;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function table(name, idKey, { include } = {}) {
|
||||
const m = t[name];
|
||||
const withIncludes = (row, inc) => {
|
||||
if (!inc) return row;
|
||||
const out = { ...row };
|
||||
if (inc._count) out._count = { importedEvents: [...t.importedEvent.values()].filter((e) => e.linkId === row.installId).length };
|
||||
if (inc.link) out.link = { ...t.productLink.get(row.linkId) };
|
||||
return out;
|
||||
};
|
||||
return {
|
||||
findUnique: jest.fn(async ({ where, select }) => { const r = m.get(where[idKey]); return r ? pick(clone(r), select) : null; }),
|
||||
findFirst: jest.fn(async ({ where, include: inc } = {}) => { const r = [...m.values()].find((x) => matches(x, where)); return r ? withIncludes(clone(r), inc) : null; }),
|
||||
findMany: jest.fn(async ({ where, select, include: inc, orderBy, take } = {}) => sortBy([...m.values()].filter((x) => matches(x, where)), orderBy).slice(0, take ?? Infinity).map((r) => withIncludes(pick(clone(r), select), inc))),
|
||||
create: jest.fn(async ({ data }) => {
|
||||
if (m.has(data[idKey])) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
|
||||
m.set(data[idKey], clone(data));
|
||||
return clone(data);
|
||||
}),
|
||||
upsert: jest.fn(async ({ where, create, update }) => {
|
||||
const prev = m.get(where[idKey]);
|
||||
const row = prev ? { ...prev, ...update } : { ...create };
|
||||
m.set(where[idKey], clone(row));
|
||||
return clone(row);
|
||||
}),
|
||||
update: jest.fn(async ({ where, data }) => {
|
||||
const prev = m.get(where[idKey]);
|
||||
if (!prev) throw Object.assign(new Error('Record to update not found'), { code: 'P2025' });
|
||||
const row = { ...prev, ...data };
|
||||
m.set(where[idKey], clone(row));
|
||||
return clone(row);
|
||||
}),
|
||||
delete: jest.fn(async ({ where }) => {
|
||||
const prev = m.get(where[idKey]);
|
||||
if (!prev) throw Object.assign(new Error('Record to delete does not exist'), { code: 'P2025' });
|
||||
m.delete(where[idKey]);
|
||||
if (name === 'productLink') for (const [k, e] of t.importedEvent) if (e.linkId === where[idKey]) t.importedEvent.delete(k);
|
||||
return prev;
|
||||
}),
|
||||
deleteMany: jest.fn(async ({ where } = {}) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of m) if (matches(r, where)) { m.delete(k); count++; }
|
||||
return { count };
|
||||
}),
|
||||
...include,
|
||||
};
|
||||
}
|
||||
|
||||
const db = {
|
||||
t,
|
||||
appSetting: table('appSetting', 'key'),
|
||||
productLink: table('productLink', 'installId'),
|
||||
linkNonce: table('linkNonce', 'nonce'),
|
||||
importedEvent: table('importedEvent', 'key'),
|
||||
feedEntry: table('feedEntry', 'eventId'),
|
||||
event: table('event', 'id'),
|
||||
campus: { findMany: jest.fn(async () => t.campus.map((c) => ({ ...c }))) },
|
||||
user: { findMany: jest.fn(async ({ where }) => t.user.filter((u) => matches(u, where))) },
|
||||
adminAuditLog: { create: jest.fn(async ({ data }) => { t.audit.push(data); return data; }) },
|
||||
reset() {
|
||||
for (const k of ['appSetting', 'productLink', 'linkNonce', 'importedEvent', 'feedEntry', 'event']) t[k].clear();
|
||||
t.campus.length = 0; t.user.length = 0; t.audit.length = 0;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = db;
|
||||
Reference in New Issue
Block a user