import http from "http"; import path from "path"; import crypto from "crypto"; import { test, expect, loginAs, seed, API } from "./fixtures"; // Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md ยง8). A fake Church Website // runs on localhost: the test tells the site the Hub listed it (as a heartbeat would), an admin // connects it and shows its events, and its event appears on /events with its own page whose // canonical link points back to the website. Also: this site's own feed, and its event JSON-LD. /* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */ const backend = path.join(__dirname, "..", "backend"); const { Client } = require(require.resolve("pg", { paths: [backend] })); const { e2eDatabaseUrl } = require("./support/db-url"); const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] })); const { eventFeedSchema } = require(require.resolve("@crosscode/contracts", { paths: [backend] })); /* eslint-enable @typescript-eslint/no-require-imports */ const WEBSITE_PORT = 5198; const WEBSITE_URL = `http://localhost:${WEBSITE_PORT}`; const WEBSITE_ID = "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02"; const EVENTS_ID = "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c"; const EVENT_ID = "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090"; const websiteKey = signing.generateEd25519(); const websitePem = signing.ed25519PublicToPem(websiteKey.publicKey); async function sql>(text: string, values: unknown[] = []): Promise { const client = new Client({ connectionString: e2eDatabaseUrl() }); await client.connect(); try { return (await client.query(text, values)).rows as T[]; } finally { await client.end(); } } const setSetting = (key: string, value: string) => sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]); function websiteEvent() { const starts = new Date(Date.now() + 10 * 24 * 3600e3); return { schema: "crosscode.event/1", id: EVENT_ID, origin: { product: "website", installId: WEBSITE_ID, url: `${WEBSITE_URL}/events/carols-by-candlelight` }, status: "published", updatedAt: new Date().toISOString(), title: "Carols by Candlelight", summary: null, description: "Bring a **blanket** and the family.\n\nNo booking needed.", imageUrl: null, timezone: "Africa/Johannesburg", startsAt: starts.toISOString(), endsAt: new Date(starts.getTime() + 2 * 3600e3).toISOString(), allDay: false, sessions: [], location: { name: "Church lawn", address: null, onlineUrl: null }, campus: null, series: null, tags: ["christmas"], registration: { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null }, }; } test.describe.serial("linked products and the event feed", () => { let server: http.Server; const connects: Record[] = []; test.beforeAll(async () => { server = http.createServer((req, res) => { let body = ""; req.on("data", c => { body += c; }); req.on("end", async () => { const send = (status: number, json: unknown) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json)); if (req.method === "POST" && req.url === "/api/links/v1/connect") { const m = JSON.parse(body); connects.push(m); // The website checks Cross Events' message with the key the Hub listed for it. const [row] = await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_public_key'`); if (!row || !signing.verifyLink(m, row.value).ok) return send(401, { message: "Bad signature", code: "BAD_SIGNATURE" }); return send(200, signing.signLink({ schema: "crosscode.link/1", type: "link.connected", from: { product: "website", installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: crypto.randomBytes(18).toString("base64url"), }, websiteKey.privateKeyPem)); } if (req.method === "GET" && req.url?.startsWith("/api/feed/v1/events")) { return send(200, { schema: "crosscode.event-feed/1", generatedAt: new Date().toISOString(), events: [websiteEvent()], deleted: [] }); } if (req.method === "POST" && req.url === "/api/links/v1/disconnect") return send(200, { schema: "crosscode.link/1", type: "link.disconnected" }); return send(404, { message: "Not here", code: "NOT_FOUND" }); }); }); await new Promise(resolve => server.listen(WEBSITE_PORT, resolve)); // What a v2 heartbeat would have stored: this site's Hub id and the church's other products. await setSetting("hub_install_id", EVENTS_ID); await setSetting("hub_linked_products", JSON.stringify([{ product: "website", installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: websitePem }])); }); test.afterAll(async () => { await sql(`DELETE FROM "ProductLink"`); await sql(`DELETE FROM "FeedEntry"`); await sql(`DELETE FROM "AppSetting" WHERE key IN ('hub_install_id', 'hub_linked_products', 'feed_publish')`); await new Promise(resolve => server.close(resolve)); }); test("an admin connects the Church Website and shows its events", async ({ page }) => { await loginAs(page, "admin"); await page.goto("/dashboard/admin/settings?tab=linked"); const row = page.getByTestId("linked-website"); await expect(row).toContainText("Church Website"); await expect(row).toContainText("Not connected"); await row.getByRole("button", { name: "Connect" }).click(); await expect(page.getByRole("status")).toContainText("Connected to Church Website."); expect(connects).toHaveLength(1); expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } }); await row.getByLabel(/Show events from Church Website/).check(); await expect(page.getByRole("status")).toContainText("events are fetched"); await expect(row).toContainText("1 event"); }); test("its event is on /events, with its own page pointing back to the website", async ({ page }) => { await page.goto("/events"); const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" }); await expect(card).toContainText("From the Church Website"); await card.getByRole("link", { name: "View details" }).click(); await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`)); await expect(page.getByRole("heading", { level: 1 })).toHaveText("Carols by Candlelight"); await expect(page.locator('link[rel="canonical"]')).toHaveAttribute("href", `${WEBSITE_URL}/events/carols-by-candlelight`); await expect(page.locator("strong", { hasText: "blanket" })).toBeVisible(); // HTML in the description is dropped, never run. expect(await page.locator("main script").count()).toBe(0); expect(await page.locator('script[type="application/ld+json"]').count()).toBe(0); const sitemap = await (await page.request.get("/sitemap.xml")).text(); expect(sitemap).not.toContain("/events/linked/"); }); test("this site's own feed and event JSON-LD", async ({ page, request }) => { const res = await request.get(`${API}/api/feed/v1/events`); expect(res.status()).toBe(200); const feed = await res.json(); expect(eventFeedSchema.safeParse(feed).success).toBe(true); const ids = feed.events.map((e: { id: string }) => e.id); expect(ids).toContain(seed().events.free); expect(ids).not.toContain(EVENT_ID); expect(JSON.stringify(feed)).not.toMatch(/@e2e\.test/); await page.goto(`/events/${seed().events.free}`); const ld = JSON.parse(await page.locator('script[type="application/ld+json"]').innerText()); expect(ld).toMatchObject({ "@context": "https://schema.org", "@type": "Event", url: expect.stringContaining(`/events/${seed().events.free}`) }); }); test("disconnecting removes its events", async ({ page }) => { await loginAs(page, "admin"); await page.goto("/dashboard/admin/settings?tab=linked"); page.once("dialog", d => d.accept()); await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click(); await expect(page.getByRole("status")).toContainText("Disconnected from Church Website."); await page.goto("/events"); await expect(page.getByTestId("linked-event-card")).toHaveCount(0); }); });